开发者

Using recursion an append in prolog

Lets say that I would like to construct a list (L2) by appending elements of another list (开发者_运维百科L) one by one. The result should be exactly the same as the input. This task is silly, but it'll help me understand how to recurse through a list and remove certain elements.

I have put together the following code:

create(L, L2) :- (\+ (L == []) -> L=[H|T], append([H], create(T, L2), L2);[]).

calling it by

create([1,2,3,4], L2)

returns

L2 = [1|create([2,3,4], **)\.

which is not a desired result.


You say that you want to understand how prolog works so I'll not give you a full solution but a hint.

Functions in prolog do not return values, they just create bindings.

When you say

append([H], create(T, L2), L2);[]).

you are trying to use a return value.

Try to have append create bindings that you use in the recursive call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜