I Tried to write a simple code in Prolog which translate a list to another list. for instance, if we call listtrans([a,b,c],L)
, L
will become [1,2,3]
. (a,b,c is replaced with 1,2,3). But i faced with a syntax error in last line. what is the problem? here is my code:
trans(a,1).
trans(b,2).
trans(c,3).
listtrans([],L).
listtrans([H|T],L1):-
trans(H,B),
append(B,L,L2),
listtrans(T,L2).
The error is very likely because in your code:
the variable
L1
is declared in the head, but not referenced anywhere: you mispelled something?Anyway, your code is not going to work.
Moreover, using
append/3
for this kind of tasks which are easily defined by recursion is considered terrible (also because of the bad performance you get out of it).Applying a function to a list is straightforward. You already know that in prolog you don't write
Y = f(X)
but rather declare the functional relation betweenX
andY
as:f(X, Y).
. (That's basically what you did withtrans(X,Y)
).Now the (easy) recursive formulation:
[X|Xs]
is[Y|Ys]
iftrans(X,Y)
and we recursively transformXs
intoYs
or expressed in prolog:
I recommend you reading the first 4 chapters of Learn Prolog Now to better understand these concepts.