Prologue; if and (stop) recursion

In an attempt to better understand the prologue, lists, and recursion in general, I work through various simple tasks that I have entrusted to myself. Among others, removing duplicate entries from a list.

I defined a rule:

is_on(Item, [Ah|At]) :- Ah = Item; is_on(Item, At).

This checks if the item is in the list X or not. So I thought I could extend this to define the filter_double predicate:

filter_doubles([Ah|At], Result) :-
    (not(is_on(Ah, At)) ->
        Result = [Ah|Result]
    ;
        filter_doubles(At, Result)
    ).

This made perfect sense to me: if Ah is not found in the rest of the list (its tail), then add a to the front of the result using the list construct, otherwise rewrite the rest of the list. Prolog seems to think differently:

47 ?- filter_doubles([1,2,3,3,4,2,1,1], Z).
Z = [3|**]. 

Am I really insisting on this?

+1
source share
2

, :

filter_doubles([], []).
filter_doubles([X|L], Result) :-
    (memberchk(X,L) ->
        filter_doubles(L, Result)
    ;
        filter_doubles(L, Result0),
        Result = [X|Result0]
    ).

Result = [Ah|Result] . Prolog " Result , Result ", ( ), " " ( , ).

: , .

, , .

+1

. , ; , , , ().

, is_on ( contains) :

contains(Item, [Item | _]).
contains(Item, [_ | Tail]) :- contains(Item, Tail).

filter_double . , .

filter_doubles([], []).

, Item Rest , Rest , Item.

filter_doubles([Item | Rest], Result) :-
    contains(Item, Rest), !,
    filter_doubles(Rest, Result).

, Item Rest ( ), Item Rest .

filter_doubles([Item | Rest], [Item | Tail]) :- filter_doubles(Rest, Tail).

, Result = [Ah|Result], Prolog : Result , Ah head Result , , Ah head Result , , Ah head Result .. .. ..

+2

All Articles