【问题标题】:prolog - why should I use 'dif' instead of '=\='prolog - 为什么我应该使用 'dif' 而不是 '=\='
【发布时间】:2020-03-22 14:53:40
【问题描述】:

我正在研究“Prolog by Example”一书中的一个例子(Helder Coelho 和 Jose C Cotta 着)。

Write a program for designing an architectural unit
obeying the following specifications:

+ Two rectangular rooms
+ Each room has a window and interior door
+ Rooms are connected by interior door
+ One room also has an exterior door
+ A wall can have only one door or window
+ No window can face north
+ Windows cannot be on opposite sides of the unit

有一个解决方案,但它在 SWI-Prolog 中不起作用,甚至无法编译。

我不得不更改书中的解决方案:使用 'dif(X,Y)' 而不是 'X =\= Y'。

有人可以解释一下:为什么原始解决方案不起作用?

这是一个代码:

plan(FD,D1,W1,D2,W2) :-
  frontroom(FD,D1,W1),
  opposite(D1,D2),
  room(D2,W2),
  notopposite(W1,W2).

frontroom(FD,D,W) :-
  room(D,W),
  direction(FD),
  dif(FD,D),     % FD =\= D,   % <- original was commented
  dif(FD,W).     % FD =\= W.   % <- original was commented

room(D,W) :-
  direction(D),
  direction(W),
  dif(D,W),      % D =\= W,     % <- original was commented
  dif(W,north).  % W =\= north. % <- original was commented

direction(north).
direction(south).
direction(east).
direction(west).

opposite(north,south).
opposite(south,north).
opposite(east,west).
opposite(west,east).

notopposite(D1,D2) :-
  opposite(D1,D3),
  dif(D2,D3).  % D2 =\= D3. % <- original was commented

我可以查询并得到答案:

?- plan(west,D1,W1,D2,W2).
D1 = east,
W1 = south,
D2 = west,
W2 = south

我正在尝试追踪原始解决方案(使用 D2 =\= D3 而不是 dif(D2,D3))并得到这个:

[trace]  ?- plan(west,D1,W1,D2,W2).
   Call: (8) plan(west, _9632, _9634, _9636, _9638) ? creep
   Call: (9) frontroom(west, _9632, _9634) ? creep
   Call: (10) room(_9632, _9634) ? creep
   Call: (11) direction(_9632) ? creep
   Exit: (11) direction(north) ? creep
   Call: (11) direction(_9634) ? creep
   Exit: (11) direction(north) ? creep
   Call: (11) north=\=north ? creep
ERROR: Arithmetic: `north/0' is not a function

为什么我不能使用 '=\='?

【问题讨论】:

  • dif 表示您创建了一个约束,以便稍后如果两个操作数接地,如果两者相同,它将失败。 =\= 意味着它应该立即不同。
  • @WillemVanOnsem:试试2 =\= 1+1. 和3 =\= 1+1
  • @commentupvoter:接地相关的说法是不正确的。在这里考虑dif(X,Y), X = Y,没有任何接地,但仍然失败。

标签: prolog prolog-dif


【解决方案1】:

应该是\== 而不是不正确的=\=。我不知道 =\= 除了算术不等式之外还有其他含义。

1982 年第 3 版是 online 和 =\= 是 even documented 与 1978 年作为 DECsystem 10 Prolog 的一部分在同一文档中。因此,即使在上述书籍的此先前版本中也存在矛盾。

到此为止。但是您绝对正确,dif/2 比(\==)/2 更可取。请参阅this 了解更多信息。

【讨论】:

  • 试图列出所有这些谓词here。这需要一点时间。
猜你喜欢
  • 2016-05-23
  • 2018-05-10
  • 2014-03-12
  • 2012-12-13
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多