问题
This predicate should print a list of size N
containing possible permutations of 0
and 1
.
My question is : does the value of H
get carried over with each recursion or does the creation of the list with values of bit(H)
take place in the backtracking phase?
bit(0).
bit(1).
gen(0,[]).
gen(N,[H|T]) :-
N > 0,
bit(H),
N1 is N - 1,
gen(N1,T).
回答1:
Prolog execution is all about choice points. Here a choice point is left at each recursion step by the bit/1
predicate.
When you ask Prolog to give you another solution, it will just go back to the youngest choice point. Here, instead of going through the first clause of bit/1
and bind H
to 0
, it will go through the second clause and bind H
to 1
. Once both clauses have been picked, Prolog'll go back to an older choice point, etc... until ultimately all choice points are exhausted and the program returns false.
.
you can try this yourself with the trace/0
predicate:
?- trace, gen(3, Result).
回答2:
May I offer you a more straight forward definition first:
gen(N, Xs) :-
length(Xs, N),
maplist(between(0,1), Xs).
In this definition all recursive parts are now hidden in some built-ins. The first goal ensures that Xs
is a list of length N
. And the next goal ensures that each element is between 0 and 1. If you look at the answers, you will realize in what order the solutions are enumerated:
?- gen(4, Xs). Xs = [0,0,0,0] ; Xs = [0,0,0,1] ; Xs = [0,0,1,0] ; Xs = [0,0,1,1] ; Xs = [0,1,0,0] ; Xs = [0,1,0,1] ; Xs = [0,1,1,0] ; ...
回答3:
This predicate generates all numbers (with order) in binary system well to understand it you must understand prolog backtracking, you coudl draw some substitution tree to understand it
来源:https://stackoverflow.com/questions/9980581/how-does-this-compute-i-am-trying-to-understand-how-the-values-of-h-get-assign