gpt4 book ai didi

Prolog语法问题,否定后的空格

转载 作者:行者123 更新时间:2023-12-05 01:36:35 25 4
gpt4 key购买 nike

我有一个关于在 SWI Prolog 中使用否定的奇怪问题。当我在否定“\+”后使用以下没有空格的代码时,会出现错误:

2 ?- assert((only_child(X) :- mother(M,X),\+(mother(M,_),\+ X==_))).
true.

3 ?- only_child(cathy).
ERROR: only_child/1: Undefined procedure: (\+)/2
ERROR: However, there are definitions for:
ERROR: (\+)/1
Exception: (7) \+(mother(melody, _G2102), \+cathy==_G2107) ? creep
4 ?-

但是,如果我在否定后使用空格,它就可以正常工作。

2 ?- assert((only_child(X) :- mother(M,X),\+ (mother(M,_),\+ X==_))).
true.

3 ?- only_child(cathy).
false.

4 ?-

但是下面的代码对两者都适用,在“\+”之后使用空格并且不使用空格。

4 ?- \+ father(michael,cathy).
false.

5 ?- \+father(michael,cathy).
false.

6 ?-

谁能给我解释一下?它真的非常令人费解。我会很感激的。

最佳答案

解析 Prolog 时,左括号是特殊的。如果标识符和左括号之间没有空格,则标识符始终被视为仿函数的名称(即使它不是字母数字)。括号内的任何内容都被视为此仿函数的参数列表。

但是,如果有空格,则括号将按其正常的分组表达式数学函数处理。此类表达式中的逗号充当 bool and 运算符的角色。

所以:

"func(A,B)"  - OK - invoke `func` on parameters `A`, `B`    
"func (A,B)" - syntax error - interpreted as an identifier stuck together
with an AND expression
"\+ (A,B)" - OK - operator `\+` acting on `(A,B)` (A and B)
"\+(A,B)" - error - invoke `\+` with two parameters `A`, `B`
but \+ only takes one argument
"\+(A)" - OK - since `\+` takes one argument, it can
be invoked as a functor with one argument inside parens

解析器也足够智能,可以将运算符从标识符中分离出来(第一个字母触发一个新的标记):

"\+ father(A,B)" - OK - invoke functor `father` with `A` and `B`, 
negate the result
"\+father(A,B)" - still OK - the parser will stop reading the
name of the operator when it encounters the 'f',
so the result is same as above

关于Prolog语法问题,否定后的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12945107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com