pvl
pvl

Reputation: 27

Prolog write list in pairs

I have a list:

[a,b,c]

I want to print the list like this:

a -> b
b -> c

So far, I have this code:

print([]).
print([H|T]) :- write(H), write(' -> '), nl, print(T).

which will produce the following result:

a -> 
b -> 
c -> 

Upvotes: 0

Views: 1117

Answers (2)

CapelliC
CapelliC

Reputation: 60004

You could consider to separate the logic - albeit minimal - from IO:

pairs([A,B|T], P) :- P = (A,B) ; pairs([B|T], P).
printp(L) :- forall(pairs(L, (A,B)), writeln(A->B)).

This way pairs/2 is ready to enumerate your sequence, in case you need to do...

Upvotes: 0

icktoofay
icktoofay

Reputation: 128991

Your predicate needs to pull more items out of the list. Try:

print([]).
print([_]).  % if we're trying to print pairs, we can't print a single item
print([X,Y|T]) :- write(X), write(' -> '), write(Y), nl, print([Y|T]).

Upvotes: 1

Related Questions