Prolog delete: doesn't delete all elements that unify with Element

前端 未结 3 1486
一个人的身影
一个人的身影 2021-01-21 07:58

I\'m having an issue with SWI-Prolog\'s delete/3 predicate. The easiest way is just a quick example:

?- delete([(1,1),(1,2),(3,2)], (1,_), List).
L         


        
3条回答
  •  星月不相逢
    2021-01-21 08:41

    " Delete all members of List1 that simultaneously unify with Elem and unify the result with List2."

    (1,X) first unifies with (1,1). therefore, X is unified with 1 and cannot be unified with 2 to delete (1,2). so the problem is not that it does not delete all of the members; it's that it doesnt unify simultaneously with (1,2) and (1,1) (try delete([(1,1),(1,2),(1,1),(3,2)],(1,_),List).

    btw, according to the swi-prolog manual:

    delete(?List1, ?Elem, ?List2)
    Is true when Lis1, with all occurences of Elem deleted results in List2.

    also, delete/3 is deprecated:

    There are too many ways in which one might want to delete elements from a list to justify the name. Think of matching (= vs. ==), delete first/all, be deterministic or not.

    So the easiest way is to write your own predicate. Something like:

    my_delete(Pattern,[Pattern|T],TD):-
       my_delete(Pattern,T,TD).
    my_delete(Pattern,[H|T],[H|TD]):-
       my_delete(Pattern,T,TD).
    

    perhaps?

    check exclude/3, include/3, partition/4

提交回复
热议问题