Is it possible to reverse a list in Prolog with only two arguments? Such as:
reverse_list(List, Reversed).
This is not homework, I’m reading Seven Programming Languages in Seven Weeks and I got curious.
With three arguments you could use an accumulator (much like in functional programming):
reverseList([], Accumulator, Accumulator).
reverseList([Head|Tail], Accumulator, Solution) :-
reverseList(Tail, [Head|Accumulator], Solution).
reverseList(List, Solution) :-
reverseList(List, [], Solution).
Clarification: I saw a solution with append, I was wondering if you could do that without other prolog functions
sure:
edit:actually that has only one :b
a non-cheating approach:
the problem is that the performance will be quite bad: you will recurse over the list and for each element you will do one append/3.
using time/1 and a random list of 1,000,000 elements: