Prolog:检查元组列表是否是一个函数

Prolog: Check if list of tuples is a function

我想检查元组列表 L (x1,y1) 是否具有函数 属性:

∀(x1,y1),(x2,y2) ∈ L (x1=x2  y1 = y2)

我尝试用以下谓词解决它:

m_Function(L) :-
    ((member(M1, L), member(M2, L), 
    M1 = (X1, Y1), M2 = (X2, Y2), X1 = X2) 
    -> Y1 = Y2).

问题是,例如输入

L = [(p, q),  (p, r)]

结果为真。

我的调试痕迹显示我更准确地实现了语句:

∃(x1,y1),(x2,y2) ∈ L (x1=x2  y1 = y2)

跟踪:

 T Call: (8) m_Function([(p, q),  (p, r)])
   Call: (8) m_Function([(p, q),  (p, r)]) ? creep
   Call: (9) lists:member(_5074, [(p, q),  (p, r)]) ? creep
   Exit: (9) lists:member((p, q), [(p, q),  (p, r)]) ? creep
   Call: (9) lists:member(_5074, [(p, q),  (p, r)]) ? creep
   Exit: (9) lists:member((p, q), [(p, q),  (p, r)]) ? creep
   Call: (9) (p, q)=(_5060, _5062) ? creep
   Exit: (9) (p, q)=(p, q) ? creep
   Call: (9) (p, q)=(_5066, _5068) ? creep
   Exit: (9) (p, q)=(p, q) ? creep
   Call: (9) p=p ? creep
   Exit: (9) p=p ? creep
   Call: (9) q=q ? creep
   Exit: (9) q=q ? creep
 T Exit: (8) m_Function([(p, q),  (p, r)])
   Exit: (8) m_Function([(p, q),  (p, r)]) ? creep

他们在序言中是否采用了一些优雅的方式,例如我可以用一些“for all”量词来解决这类问题?

您可以使用 forall/2.

m_Function(L) :-
    forall((member((X, Y1), L), member((X, Y2), L)), Y1 == Y2).

forall(Condition, Action) succeeds if for all alternative bindings of Condition, Action can be proven. It is equivalent to \+(Condition, \+ Action).