Amir Jalilifard
Amir Jalilifard

Reputation: 2059

How to concat two lists in Prolog

I was reading a prolog code about concatenation of two lists. It works well but I cannot understand how it works :

concatenation([ ], Lista, Lista).
concatenation([ Elem | Lista1], Lista2, [Elem | Lista3]):-
                                     concatenation(Lista1, Lista2, Lista3).
?-concatenation([one, two], [three, four],L).
**Result : [one,two,three,four]**

First I cannot understand that in the goal part we have

**concatena([ Elem | Lista1], Lista2, [Elem | Lista3])**

I really cannot understand why instead of putting a normal variable and then handling the other calculations in the right side of ":-", it is starting to get the head and tail in the Goal part!

The second question is that how this recursion can give the next element of each lists in each iteration?

So my question is that how this algorithm works step by step. Thanks

Upvotes: 1

Views: 4196

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

I find that it helps me to read Prolog from Right To Left (which I guess is natural from both our native tongues anyway, I guess).

So the first part says:

concatenation([ ], Lista, Lista).

or: regardless of anything (the right-hand-side is empty), you can always concatenate an empty list to some list to obtain the same list.

Now the second part says, starting from the right,

concatenation(Lista1, Lista2, Lista3)

meaning you can concatenate Lista1 to Lista2, obtaining Lista3.

and then the entire second part says

concatenation([ Elem | Lista1], Lista2, [Elem | Lista3]):-
    concatenation(Lista1, Lista2, Lista3).

meaning: if you can concatenate Lista1 to Lista2, obtaining Lista3, then you can concatenate Lista1 prepended by Elem to Lista2, obtaining Lista3 prepended by Elem.

Upvotes: 3

Related Questions