为什么 SWI-Prolog 将带引号和不带引号的字符串(不含空格)统一为同一规则?
假设我有以下规则:
unify('test', 'this is a test').
run :- write('Enter something: '),
read(X),
unify(X, Y),
write('The answer is '), write(Y).
然后我按如下方式运行它:
?- ['unify.pl'].
% unify.pl compiled 0.00 sec, -48 bytes
true.
?- run.
Enter something: test.
The answer is this is a test
true.
?- run.
Enter something: 'test'.
The answer is this is a test
true.
为什么 SWI-Prolog 将 test
和 'test'
统一为 unify('test' ,“这是一个测试”)。
?我在回答有关 SO 的 Prolog 问题时遇到了这一点。虽然我能够回答这个人的问题,但我无法解释这种特殊行为,而且我想知道其他人是否可以。
Assume I have the following rules:
unify('test', 'this is a test').
run :- write('Enter something: '),
read(X),
unify(X, Y),
write('The answer is '), write(Y).
And then I run it as follows:
?- ['unify.pl'].
% unify.pl compiled 0.00 sec, -48 bytes
true.
?- run.
Enter something: test.
The answer is this is a test
true.
?- run.
Enter something: 'test'.
The answer is this is a test
true.
Why does SWI-Prolog unify both test
and 'test'
to unify('test', 'this is a test').
? I came across this while answering a Prolog question on SO. While I was able to answer the person's question, I couldn't explain this particular behavior, and I was wondering if any one else could.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然 SWI-PROLOG 中的原子可以使用单引号表示,例如,
'这是一个原子'
,但当 SWI-PROLOG 解析器可以识别一个原子时,不需要单引号。字符序列中的原子,通常以小写字母字符开头,例如test
。如果序列包含空格(或其他一些字符),则需要单引号来正确表示原子。字母数字字符和某些标点符号(例如下划线_
)都可以,例如test5_6
。如果不带单引号的字符序列以其他任何内容开头,例如数字
6k
,解析器会将其视为数字
;如果它是大写字母字符,例如Test
,解析器会将其视为变量。While atoms in SWI-PROLOG can be denoted using single quotes, e.g,
'This is an atom'
, single quotes are not needed when the SWI-PROLOG parser can identify an atom from a sequence of characters, usually starting with a lowercase alphabetic character, such astest
. If the sequence contained whitespace (or some other characters), you'd need the single quotes to denote an atom properly. Alphanumeric characters and certain punctuation characters like underscore_
are fine, e.g.,test5_6
.If the character sequence without single quotes were to start with anything else, such as a number
6k
, the parser will treat it as anumber
; if it were an uppercase alphabetic character such asTest
, the parser will treat it as a variable.这不是 SWI 特定的行为 - 这是标准所要求的。
有一个简单的方法可以看到这一点。您也可以将其用于
语法不明显的任何其他术语。在顶层键入:
答案始终是有效的 Prolog 文本 - 这是特定于 SWI 的,但是
也适用于许多其他 Prolog 系统,如 YAP、GNU、B、IF、SICStus。
另一种查看此情况的方法是使用 write_canonical/1:
This is not SWI specific behavior - it is required by the standard.
There is a simple way to see this. You can use this also for
any other term whose syntax is not evident. Either type at the toplevel:
The answer is always valid Prolog text - this is specific to SWI but
also to many other Prolog systems like YAP, GNU, B, IF, SICStus.
Another way to see this is to use write_canonical/1: