Reputation: 53
I'm having trouble understanding how prolog works with lists. I'm trying to write a function that will add a tail to a given list and returns a new list. but my implementation does not work and I can't understand how to fix it. Here is what I have:
% add_tail(L,M,E) :- L is M with [E] appended.
% I wanna do this without using the append predicate
add_tail([E],[],E).
add_tail(List, [H|T], E):-
add_tail(List1, T, E),
List is [H|List1].
to clarify what i want this function to do, here is an example of an output:
?- add_tail(L,[1,2,3],4).
L = [1,2,3,4].
Upvotes: 2
Views: 2199
Reputation: 11378
Check this out:
append([X|Y],Z,[X|W]) :- append(Y,Z,W).
append([],X,X).
The second line (append([],X,X)
) simply states that appending an element X
to an empty list is equal to that element itself (break condition). The first line states appending Z
to a list [X|Y]
(X
is head, Y
rest) results in a new list [X|W]
, whereas W
is the result of appending Z
to Y
.
Example
?- append([1,2,3],[4],L).
L = [1,2,3,4]
In your case you just need to reorder the parameters!
Upvotes: 1