2
votes

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!

1
You can't embed predicate calls such as turn(listv(X), R). And what does that predicate/fact mean? It has two variables that aren't defined. You would need something like, turned_lists(P, Result) :- call(P, L), turn(L, Result). and call it as, turned_lists(alist, Result). or something like that, all depending upon what you're trying to achieve exactly (which isn't totally clear).lurker
Oops, those are queries for existing predicates I've already made! Sorry for the lack of clarity there.RockMan

1 Answers

2
votes

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].