2
votes

I'm learning Prolog via learnprolognow. Currently I'm on chapter4 and am stuck on the second exercise.

"Now write a 3-place predicate combine2 which takes three lists as arguments and combines the elements of the first two lists into the third as follows:

?-  combine2([a,b,c],[1,2,3],X).    
X  =  [[a,1],[b,2],[c,3]] "

My implementation of this is:

combine2([],[],[]).
combine2([H1|T1],[H2|T2],[[H1,H2],R]):-
   combine2(T1,T2,R).

The result of the query above tho is:

 X = [[a, 1], [[b, 2], [[c, 3], []]]] ;

I do not know how to re-write it, so in the last step the program is not adding an empty list. I am open to suggestions/hints/solutions.

Thank you and have a nice sunday!

2

2 Answers

2
votes

In your implementation: [[H1,H2],R] is a list with two elements the element [H1,H2] and the element R. What you need to write is [[H1,H2]|R] which represents a list of head element [H1,H2] and the rest of the list R which will be recursively instantiated. Note that the line [[H1,H2],R] does not only cause an empty list in the end but it also nests your list because you are not getting X = [[a, 1], [b, 2], [c, 3], []] ; (which just has an empty list) but nested lists like: X = [[a, 1], [[b, 2], [[c, 3], []]]] ;

2
votes

You have to change only a char: | instead of , in [[H1,H2],R]: i mean, [[H1,H2]|R] instead of [[H1,H2],R].

If you use a comma, you create a new list with two elements: (a) the list [H1,H2] and (b) the list R

If you use a pipe, you insert (in first position) the list [H1, H2], followed by elements in R.