Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

lists

Status
Not open for further replies.

michaela1

Programmer
Mar 22, 2008
2
IE
Hi

I am trying to teach myself prolog and as I am totally new to this I thought some help wouldn't be a bad idea.
My first challenge is to write a prolog predicate that takes two arguments. The first is a list and the predicate should return the list reversed as the second argument.
e.g

reverse([a,b,c,d], X).
X=[d,c,b,a]
Can anyone help to get me started?

I know a is the head and b,c,d is the tail but don't know where to go from there...
 
one way is to use the built-in predicate append.

...if you have an empty list, the result is an empty list [],
otherwise, you want to take the head [a] and concatenate it to the reverse of the tail [b,c,d].

base case: rev([],[]).

recursive step: rev([H|T],R]) :- rev(T,X),append(X,[H],R).

this is correct but inefficient. there is a better way of doing it using an accumulator. the tutorial Learn Prolog Now! does a good job at explaining these two methods of reversing a list.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top