user287474
user287474

Reputation: 325

List to Tuples in Prolog

I'm trying to write a clause in Prolog that takes in a list and returns predicates of edges. For example:

?- listpairs([1, 2, 3], X, Y).
X = 1
Y = 2;

X = 2
Y = 3;

This is what I've tried so far and haven't been getting anywhere.

listpairs([H], H, H).
listpairs([H1,H2|T], X, Y) :- 
      X is H1,
      Y is H2,
      listpairs([H2|T], X, Y).

I would appreciate it if someone could help.

Upvotes: 2

Views: 1126

Answers (1)

coder
coder

Reputation: 12972

The problem is that by writing:

X is H1,
Y is H2

X,Y get instantiated which means that their value can't change further so your predicate will fairs since in next iteration of recursion you try to re-instantiate X,Y.

Try:

listpairs([H1,H2], H1, H2).
listpairs([H1,H2,_|_], H1, H2).
listpairs([_,H2|T], X, Y) :- listpairs([H2|T], X, Y).

Example:

?- listpairs([1, 2, 3, 4, 5], X, Y).
X = 1,
Y = 2 ;
X = 2,
Y = 3 ;
X = 3,
Y = 4 ;
X = 4,
Y = 5 ;
false.

Upvotes: 2

Related Questions