Prolog doesn't return a value

I have the following code:

pair_list([X,Y],[[X,Y]]).
pair_list([E,Z|X],[K|Y]):- [E,Z]==K, pair_list(X,Y).

When I run it, it gives correct output for

?- pair_list([1, 2, 3, 4, 5, 6], [[1, 2], [3, 4], [5, 6]]).
true ;

but when I run

?- pair_list([1,2, 3, 4, 5, 6], X).

I just get false.

My question is why don't I get X=[[1, 2], [3, 4], [5, 6]]

Upvotes: 3

Views: 206

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

You are almost there: all you need to do is moving [E,Z] into the head, eliminating K:

pair_list([X,Y],[[X,Y]]).
pair_list([E,Z|X],[[E,Z]|Y]) :- pair_list(X,Y).

Demo 1.

Note that the base clause can be replaced with one based on empty lists:

pair_list([], []).
pair_list([E,Z|X],[[E,Z]|Y]) :- pair_list(X,Y).

Demo 2.

Also note that your program is not going to work with a list that has an odd number of items. In order to fix this, add a separate base clause that handles a list with a single item either by dropping the item, making a pair with some fixed atom, or doing something else that you find useful in this case.

Upvotes: 3

Related Questions