开发者

Using recursion an append in prolog

开发者 https://www.devze.com 2022-12-24 18:18 出处:网络
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.

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

精彩评论

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