list - How does Prolog handle this query -
this question has answer here:
- recursion in prolog (on lists) 4 answers
considering following definition:
my_append([], l, l). my_append([h|t], l, [h|newtail]):- my_append(t, l, newtail).
and possible usage, , output:
?- my_append([1,2,5], [3,4], l). l = [1, 2, 5, 3, 4].
could me understanding how work?
this recursive function.
it splits first list head pieces , when empty takes second list , successively adds head front.
you can imagine multiple calls my_append follows:
my_append([1,2,5], [3,4], l)
which calls:
my_append([2,5], [3,4], l)
which calls:
my_append([5], [3,4], l)
which calls base case:
my_append([], [3,4], l)
this returned in reverse order follows:
l [3,4], l [5,3,4], l [2,5,3,4], l [1,2,5,3,4] , function ends.
Comments
Post a Comment