How do I append lists in Prolog? I've searched on the Internet and I found this (from http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/2_7.html)
append([X|Y],Z,[X|W]) :- append(Y,Z,W).
append([],X,X).
So it gets the Z
by removing the elements of [X|Y]
in [X|W]
. But how do I append two lists together?
Example,
appendlist([1,2],[3,4,5],X).
The result will be X = [1,2,3,4,5]
.
Also I don't know what happening in the recursion. (I traced it but didn't understand)
EDIT: What I want to know is how it should be coded to function like the predefined append()
in Prolog.
You answered your own question: You use
append/3
.If you want to append
X
andY
and store the result inZ
, you doIf for example
X = [1, 2]
andY = [3, 4, 5]
thenZ
will be bound to[1, 2, 3, 4, 5]
:The code as you've posted it is (almost) OK. The order of clauses just needs to be swapped (in order to make this predicate definition productive, when used in a generative fashion):
This defines a relationship between the three arguments, let's say
A
,B
andC
.Your first line says, "
C
is the result of appendingA
andB
ifA
andC
are non-empty lists, they both have the same head (i.e. first element), and the tail ofC
is the result of appending the tail ofA
with the same 2nd argument,B
".Or from left to right:
Think about it, it makes perfect sense. What it does is, we want to define the
append/3
relationship, and we know what we want it to be, so we just write down some obvious facts about it that we want it to fulfill, the laws that it must follow if you will.So assuming we have this code already defined for us, what laws must it follow? Obviously, appending a tail of some list with another list gives us a tail of result of appending the full list with that 2nd list.
This defines how we "slide along" the first list. But what if there's nowhere more to slide? What if we've reached the end of that list? Then we've arrived at the empty list, and appending an empty list with another list gives us that list as the result. Obviously. And that's what that 2nd line in your code is telling us, it says, "appending an empty list with another list produces that list as the result".
Amazingly, having written down these two laws that
append/3
must follow, is the same as writing down the definition itself.addition: this explains it from a declarative point of view; do check out an answer by m09 which shows it more from the operational point of view.