Remove duplicates in list (Prolog)

后端 未结 9 2088
鱼传尺愫
鱼传尺愫 2020-11-27 08:02

I am completely new to Prolog and trying some exercises. One of them is:

Write a predicate set(InList,OutList) which takes as input an arbitrary l

相关标签:
9条回答
  • 2020-11-27 08:27

    You just have to stop the backtracking of Prolog.

    enter code here
    member(X,[X|_]):- !.
    member(X,[_|T]) :- member(X,T).
    
    set([],[]).
    set([H|T],[H|Out]) :-
       not(member(H,T)),
       !,
    set(T,Out).
    set([H|T],Out) :-
       member(H,T),
       set(T,Out).
    
    0 讨论(0)
  • 2020-11-27 08:33

    A simpler (and likely faster) solution is to use library predicate sort/2 which remove duplicates in O(n log n). Definitely works in Yap prolog and SWIPL

    0 讨论(0)
  • This works without cut, but it needs more lines and another argument. If I change the [H2|T2] to S on line three, it will produce multiple results. I don't understand why.

    setb([],[],_).
    setb([H|T],[H|T2],A) :- not(member(H,A)),setb(T,T2,[H|A]).
    setb([H|T],[H2|T2],A) :- member(H,A),setb(T,[H2|T2],A).
    setb([H|T],[],A) :- member(H,A),setb(T,[],A).
    set(L,S) :- setb(L,S,[]).
    
    0 讨论(0)
提交回复
热议问题