代码之家  ›  专栏  ›  技术社区  ›  Martin Kunze

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

  •  0
  • Martin Kunze  · 技术社区  · 4 年前

    我想检查元组列表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
    

    他们在序言中是否有一些优雅的方式,例如使用一些“所有人”量词,我可以用它们来解决这类问题?

    0 回复  |  直到 4 年前
        1
  •  1
  •   rajashekar    4 年前

    你可以用 forall/2 .

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

    forall(Condition, Action) 如果条件的所有可选绑定都可以证明操作,则成功。相当于 \+(Condition, \+ Action) .

    推荐文章