views:

175

answers:

1

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.

+3  A: 

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.

charlieb
Thank you for your response. I came out with this line:remove1(L, L2) :- display(L2), (\+ (L == []) -> L=[H|T], append(L2, H, L2), remove1(T, L2); []).However, I get error: _G256ERROR: Out of global stackWhy is that?
Adrian
I must confess that I am more familiar with the more conventional prolog syntax where each predicate is declared once for each argument structure. I can say this though, when you get an out of stack error it means that your recursion has failed to terminate. This is either because your termination criteria are wrong or that the rest of your program isn't reducing the arguments the way you think it should. In this case I suspect the latter and would advise you to look closely at the append because it seems to me that you probably don't want L2 on both sides.
charlieb