Prolog list difference routine

前端 未结 4 885
北海茫月
北海茫月 2020-12-18 01:17

I am trying to implement a list difference routine in prolog. For some reason the following fails:

difference(Xs,Ys,D) :- difference(Xs,Ys,[],D).
difference(         


        
相关标签:
4条回答
  • 2020-12-18 01:32
    always (subtructLists(List, [Head|Rest], Result): -
           ( 
              delete_element(Head, List, Subtructed)
            , !
            , subtructLists(Subtructed, Rest, Result)
           ) ; (
              subtructLists(List, Rest, Result)
           )
    ).
    
    always (subtructLists(List, [], List)).
    
    always( delete_element(X, [X|Tail], Tail)).
    
    always( delete_element(X, [Y|Tail1], [Y|Tail2]): -
            delete_element(X, Tail1, Tail2)
    ).
    
    0 讨论(0)
  • 2020-12-18 01:35

    Your usage A1 is [X|A] is incorrect. Predicate is is used only for arithmetics. Btw, SWI-Prolog has built-in subtract predicate:

    1 ?- subtract([1,2,3,a,b],[2,a],R).
    R = [1, 3, b].
    
    2 ?- listing(subtract).
    subtract([], _, []) :- !.
    subtract([A|C], B, D) :-
            memberchk(A, B), !,
            subtract(C, B, D).
    subtract([A|B], C, [A|D]) :-
            subtract(B, C, D).
    
    true.
    

    Is this what you need?

    0 讨论(0)
  • 2020-12-18 01:36
    minus([H|T1],L2,[H|L3]):-
        not(member(H,L2)),
        minus(T1,L2,L3).
    minus([H|T1],L2,L3):-
        member(H,L2),
        minus(T1,L2,L3).
    minus([],_,[]). 
    

    minus([1,2,3,4,3], [1,3], L).
    
    output: L=[2,4]
    
    0 讨论(0)
  • 2020-12-18 01:37

    Using find all the solution becomes obvious:

    difference(Xs,Ys,D) :- 
      findall(X,(member(X,Xs),not(member(X,Ys))),D).
    
    0 讨论(0)
提交回复
热议问题