【问题标题】:Prolog: How to check whether each member of the list has a property?Prolog:如何检查列表的每个成员是否具有属性?
【发布时间】:2019-01-13 07:07:36
【问题描述】:

在第 32 页的“Prolog by Example: How to Learn, Teach and Use it”一书中:

检查列表的所有元素是否满足某些属性(即一元谓词)。

逻辑程序:

satisfy_property([], _). satisfy_property([X|L], P) :- R=..[P,X],R, satisfy_property(L,P).

beautiful(mary). 
beautiful(anne). 
beautiful(louise).

执行:

?-satisfy_property([mary, anne, louise], beautiful). 
Yes

帮助修改程序逻辑: 如何检查列表中的每个成员?

【问题讨论】:

  • “每个成员”是什么意思。您正在使用您的查询递归所有事实。
  • 它应该像这样工作:?-satisfy_property([mary, tom, anne, louise], beautiful)。真的;错误的;真的;真的;

标签: prolog


【解决方案1】:

这是否如您所愿?

satisfy_property([], _).
satisfy_property([X|L], P) :-
    var(X),
    !,
    write("false "),
    satisfy_property(L,P).
satisfy_property([X|L], P) :-
    R=..[P,X],
    R,
    write("true "),
    satisfy_property(L,P).
satisfy_property([X|L], P) :-
    R=..[P,X],
    not(R),
    write("false "),
    satisfy_property(L,P).

beautiful(mary). 
beautiful(anne). 
beautiful(louise).

?-satisfy_property([mary, tom, TOM, anne, louise], beautiful). 

这给了我:

真假假真真是的。

【讨论】:

  • @Lucky - 然后你会投票并接受作为答案。 :-)
  • 当然可以,但是:“感谢您的反馈!声望低于 15 人的投票会被记录下来,但不要更改公开显示的帖子得分。”
【解决方案2】:

大多数 Prolog 系统都有maplist/2 predicate [swi-doc]

所以我们可以将谓词定义为:

satisfy_property(L, P) :-
    maplist(P, L).

或者我们可以自己实现谓词:

satisfy_property([], _).
satisfy_property([H|T], P) :-
    call(P, H),
    satisfy_property(T, P).

call/2 [swi-doc] 是一个 ISO 谓词。

【讨论】:

  • 谢谢!我使用了谓词“apply”,但它仍然不是解决方案:six_property([], _)。满足属性(P,[H|T]):- 应用(P,[H]);满足属性(P,T)。执行:?-satisfy_property(美丽,[玛丽,汤姆,安妮,路易丝])。真的;真的;真的;错误的。汤姆未经过验证。
  • @Lucky:但在这里你使用“逻辑或”(;)而不是“逻辑与”(,)。
  • @Lucky:您还交换了基本案例和递归案例中的参数。
  • 感谢您的详细评论。这些信息对我很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-28
相关资源
最近更新 更多