Reputation: 53
I've created a function in Prolog to "turn" a list, e.g. to append the head of a list to the tail like so:
?- turn([a,b,c,d,e], Tlist).
Tlist=[b,c,d,e,a]
Within the context of my program, I'd like to be able to use predefined lists for the rule, such as
alist([a,b,c,d,e,f])
but I get lots of different errors. I've tried the following as arguments:
turn(alist(L),R).
listv(X) :- alist(L), member(X, L).
turn(listv(X),R).
and I understand that each of these are different representations of the list according to Prolog, but I'm not sure which list representation is appropriate to complete the operation on a predefined list.
Thanks!
Upvotes: 2
Views: 2655
Reputation: 18726
The predicate turn/2
can easily be defined based on append/3
:
turn([A|As],Bs) :-
append(As,[A],Bs).
For specifying some sample lists, we define an auxiliary predicate named_list/2
:
named_list(one_to_nine , [1,2,3,4,5,6,7,8,9]).
named_list(a_to_f , [a,b,c,d,e,f]).
named_list(single_digit_primes, [2,3,5,7]).
Let's query!
?- named_list(a_to_f,Xs), turn(Xs,Ys). Xs = [a,b,c,d,e,f], Ys = [b,c,d,e,f,a]. % succeeds deterministically ?- named_list(a_to_f,Ys), turn(Xs,Ys). % "other" direction Ys = [a,b,c,d,e,f], Xs = [f,a,b,c,d,e] % succeeds leaving behind choicepoint ; false.
So far, we have used one specific sample list a_to_f
in the queries; let's use 'em all!
?- named_list(Name,Xs), turn(Xs,Ys). Name = one_to_nine , Xs = [1,2,3,4,5,6,7,8,9], Ys = [2,3,4,5,6,7,8,9,1] ; Name = a_to_f , Xs = [a,b,c,d,e,f] , Ys = [b,c,d,e,f,a] ; Name = single_digit_primes, Xs = [2,3,5,7] , Ys = [3,5,7,2].
Upvotes: 2