Using recursion is added in the prolog

Suppose I would like to build a list (L2) by adding the elements of another list (L) one by one. The result should be exactly the same as the input. This task is stupid, but it will help me understand how to go through the list and remove certain items.

I have compiled the following code:

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

calling him

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

returns

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

which is not the desired result.

+4
source share
1 answer

You say that you want to understand how the prologue works, so I will not give you a complete solution, but hints.

Functions in the prolog do not return values; they simply create bindings.

When you speak

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

You are trying to use the return value.

Try adding the binding functions that you use in the recursive call.

+3
source

Source: https://habr.com/ru/post/1305395/


All Articles