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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reverse_list

Status
Not open for further replies.

xristiana

Programmer
Oct 23, 2010
48
GR
Hi, I don't understand how this programm works.

reverse_list([], []).
reverse_list([Head | Tail], ReversedList) :-
reverse_list(Tail, ReversedTail),
append(ReversedTail, [Head], ReversedList).

It is assumed to reverse a list, but I don't know what calls does it make and with what order. Can anyone help me? I tried to run it on Swi-Prolog, but it didn' t help me. Thank you.
 
I suggest you try debugging it in SWI-Prolog to see what happens. Type:

?- guitracer.

at the Prolog prompt. Then type this:

?- trace, reverse_list([5]).
?- trace, reverse_list([5, 6]).
?- trace, reverse_list([5, 6, 7]).

If you understand reversal of 1-element lists, it would be easier to understand reversal of 2-element lists, then 3-element lists and then N-element lists. It's recursivity.

In case you don't have experience with debugging, the green line shows where execution is, and somewhere in the upper left part of the debug window you'll see all the variables involved. To move one step forward with the execution, press SPACE and watch closely how variables are affected.
 
When I put trace, reverse_list([5]). ,it says undefined reverse_list/1, however there is a definition for reverse_list/2.
 
Right, it's my fault ...

Type these instead:

?- trace, reverse_list([5], Result).
?- trace, reverse_list([5, 6], Result).
?- trace, reverse_list([5, 6, 7], Result).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top