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

前端 未结 3 1488
一个人的身影
一个人的身影 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:26

    This answer tries to generalize the idea presented in previous answer.

    Let's define a reified variant of subsumes_term/2:

    list_nonvardisj([A],C) :- 
       !, 
       C = nonvar(A).
    list_nonvardisj([A|As],(nonvar(A);C)) :-
       list_nonvardisj(As,C).
    
    subsumes_term_t(General,Specific,Truth) :-
       subsumes_term(General,Specific),
       !,
       term_variables(General,G_vars),
       free4evrs(G_vars),
       Truth = true.
    subsumes_term_t(General,Specific,Truth) :-
       Specific \= General,
       !,
       Truth = false.
    subsumes_term_t(General,Specific,Truth) :-
       term_variables(Specific,S_vars),
       (  S_vars = [V]
       -> freeze(V,subsumes_term_t(General,Specific,Truth))
       ;  S_vars = [_|_]
       -> list_nonvardisj(S_vars,S_wakeup),
          when(S_wakeup,subsumes_term_t(General,Specific,Truth))
       ;  throw(error(instantiation_error, subsumes_term_t/3))
       ),
       (  Truth = true
       ;  Truth = false
       ).
    

    The above definition of the reified predicate subsumes_term_t/3 uses free4evrs/1 to ensure that the "generic" term passed to subsumes_term/2 is not instantiated any further.

    For SICStus Prolog, we can define it as follows:

    :- module(free4evr,[free4evr/1,free4evrs/1]).
    
    :- use_module(library(atts)).
    
    :- attribute nvrb/0.                       % nvrb ... NeVeR Bound
    
    verify_attributes(V,_,Goals) :-
       get_atts(V,nvrb), 
       !,
       Goals = [throw(error(uninstantiation_error(V),free4evr/1))].
    verify_attributes(_,_,[]).
    
    attribute_goal(V,free4evr(V)) :-
       get_atts(V,nvrb).
    
    free4evr(V) :-
       nonvar(V),
       !,
       throw(error(uninstantiation_error(V),free4evr/1)).
    free4evr(V) :-
       (  get_atts(V,nvrb)
       -> true
       ;  put_atts(Fresh,nvrb),
          V = Fresh
       ).
    
    free4evrs([]).
    free4evrs([V|Vs]) :-
       free4evr(V),
       free4evrs(Vs).
    

    Let's put subsumes_term_t/3 to use!

    ?- texclude(subsumes_term_t(1-X), [A,B,C], Fs), A = 1-1, B = 1-2, C = 3-2.
    A = 1-1, B = 1-2, C = 3-2, Fs = [C], free4evr(X) ? ;   % succeeds with choice-point
    no
    
    ?- texclude(subsumes_term_t(1-X), [x,1-Y,2-3], Fs).
    Fs = [x,2-3], free4evr(X) ? ;
    no
    

    What happens if we instantiate variable X in above query sometime after the call to texclude/3?

    ?- texclude(subsumes_term_t(1-X), [x,1-Y,2-3], Fs), X=something.
    ! error(uninstantiation_error(something),free4evr/1)
    

提交回复
热议问题