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!

Rotate a list once to the right... 1

Status
Not open for further replies.

gomer555

Programmer
Nov 18, 2008
3
US
Hello all. I am pretty new to prolog and understanding it so-so thus far. I have question, which seems simple, but i have not been able to come up with a solution. Its as follows:

Given a list, rotate it to the right. An example query is rotate([1,2,3], R). => R=[3,1,2]; false. There is also the constraint of only defining one predicate.

When i first read the question, i thought to myself this is simple, just get the last element of the list and move it up front. Sadly, i have not been able to do it.

Thanks for any help, and hopefully this doesn't make anyone laugh!
 
Nobody laugh !
You just need a predicate rotate/3 which read the list and give the last element of it and a new list which is the initial list without the last element.

I give you a tip :
Code:
% go_through(+L1, -L2)
% go_through a list and built the result
% when leaving the recursion
go_through([], []).
go_through([H | T], [H | T1]) :-
	go_through(T, T1).
You should use 'trace' to see how the result is built.
rotate/3 is similar to go_through.
 
hmm, i tried to do what you've said but i havent been able to get what i want. Here is what i got so far, it will return the last element of the list, and also the list without the last element:

rotate([H], [], H).
rotate([H|T], [H|T1], R) :- rotate(T, T1, R).

example query:
rotate([1,2,3], R, L).
R = [1, 2],
L = 3 ;
false.

All i need to do is put L in the list R, but when i try to do that, i get distorted results. Am i on the right track?
 
Am i on the right track ?" Yes, you are.
As in Lisp, in Prolog, you can access at the first element and the rest of a list with [Head | Tail].
So in rotate/2, you build the rotate list with the elements you get in rotate/3.
 
Got it! Thanks a ton for the help joel, turned out to be a pretty easy solution after you figure it out, but isnt everything!

rotate(List, R):- rotate(List, R1, H), R = [H|R1].
rotate([H], [], H).
rotate([H|T], L, R) :- rotate(T, T1, R), L = [H|T1].
 
Prolog is hard to understand at the beginning, but very pleasant after !
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top