I'm trying to reverse a list in Prolog. It works OK when I call it with ['item1', 'item2']
but not when calling it with ['item1'|'item2']
. I'm at beginner level with Prolog, but I thought that these two notations were essentially interchangeable?
Here's the code I'm using:
reverse_list([], Acc, Acc).
reverse_list([Head|Tail], Acc, Reversed) :-
reverse_list(Tail, [Head|Acc], Reversed).
reverse_list(List,Reversed) :-
reverse_list(List,[],Reversed).
The problem is when making the recursive call with the tail of the list
When I call it with list ['item1', 'item2']
, the debugger shows that it works correctly, making a recursive call with the tail as ['item2']
, as it should be.
When I call it with ['item1'|'item2']
, the debugger shows that it tries to make a recursive call with 'item2', which fails, presumably because it's not a list.
I read that the Tail will always be a list when using [Head|Tail]
, but it looks like that isn't the case here.
Could you explain how Prolog is handling these lists, and why these two ways of representing lists aren't interchangeable? Could you explain how to make this code work?
Thanks!
[First | Rest]
. So, in[1,2,3,4]
,First = 1
andRest = [2,3,4,5]
. – AJFfoldl
. first,cons(X,Xs,[X|Xs]).
, thenreverse(A,B) :- foldl(cons, A, [], B)
. – AJF