Reputation: 738
I am very new to Prolog. My goal is to append integers to a list, up to a bound:
if the function receives N
, it outputs a list [N, N-1, ... , 1]
.
Here is my code:
myAppend(0, L) :- append([],[], L).
myAppend(N, L) :- append([N], [], L), N1 is N - 1, myAppend(N1, L).
invoking the function above returns false for every N=\=0
:
51 ?- myAppend(0,L).
L = [] ;
false.
52 ?- myAppend(2,L).
false. <-------------------- was expecting L = [2, 1]
53 ?-
However, when i changed my function to (put a dot .
instead of ,
after call to append
in the 2nd rule):
myAppend(0, L) :- append([],[],L).
myAppend(N,L) :- append([N], [], L). N1 is N - 1, myAppend(N1, L).
I got the following output:
51 ?- myAppend(0,L).
L = [] ;
false.
52 ?- myAppend(4,L).
L = [4] . <-------------- was expecting [4, 3, 2, 1]
53 ?-
I am unable to understand why in the 1st implementation I was receiving false
, although the logic behind it is correct?
Upvotes: 0
Views: 1752
Reputation: 66230
What about
myAppend(0, []).
myAppend(N, [N | L]) :-
N > 0,
N1 is N - 1,
myAppend(N1, L).
?
Upvotes: 1