开发者

Creating a 'remove member' function in prolog

I am new to Prolog and I开发者_如何学C'm trying to to create function that will simply remove all instances of an element from a list. The following code is what I have so far:

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

When I run this code on:

remove([1,2,3,4,5], 3, L2).

i get an error:

ERROR: Out of global stack

Could someone point me to why I am getting this problem?


This statement

[H|T] == []

can never be true because an empty list can never be identical to a list that contains at least one element.


What you need is a SWI's subtract predicate:

 ?- subtract([1,1,2,3,1],[1,2],R).
R = [3].

 ?- listing(subtract).
lists:subtract([], _, []) :- !.
lists:subtract([A|C], B, D) :-
        memberchk(A, B), !,
        subtract(C, B, D).
lists:subtract([A|B], C, [A|D]) :-
        subtract(B, C, D).

true.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜