Translating a list to another list in prolog -
i tried write simple code in prolog translate list list. instance, if call listtrans([a,b,c],l), l become [1,2,3]. (a,b,c replaced 1,2,3). faced syntax error in last line. problem? here 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 because in code:
listtrans([h|t],l1):- trans(h,b), append(b,l,l2), listtrans(t,l2). the variable l1 declared in head, not referenced anywhere: mispelled something?
anyway, code not going work.
moreover, using append/3 kind of tasks defined recursion considered terrible (also because of bad performance out of it).
applying function list straightforward. know in prolog don't write y = f(x) rather declare functional relation between x , y as: f(x, y).. (that's did trans(x,y)).
now (easy) recursive formulation:
- the transformed empty list empty list
- the transformation of
[x|xs][y|ys]iftrans(x,y), recursively transformxsys
or expressed in prolog:
listtrans([],[]). listtrans([x|xs],[y|ys]) :- trans(x,y), listtrans(xs,ys). i recommend reading first 4 chapters of learn prolog now better understand these concepts.
Comments
Post a Comment