Prolog:单项与单项列表

The*_*111 5 prolog

在为学校排除更大的作业时,我发现了一个错误,我在处理单个项目列表(一个项目的堆栈),好像它是一个单项.我解决了我的问题,但是在进一步测试中我发现了一些奇怪的东西:

48 ?- 1 is [1].
true.

49 ?- -1 is [-1].
ERROR: is/2: Type error: `character' expected, found `-1'

50 ?- 0.66 is [0.66].
ERROR: is/2: Type error: `character' expected, found `0.66'
Run Code Online (Sandbox Code Playgroud)

使用=:=/2而不是/ 2发生类似的行为.因此,无论出于何种原因,单个项目列表被视为与单个项目相同,但仅适用于非负整数.

好奇心比什么都重要......有谁知道这是为什么?

谢谢!

小智 4

SWI-Prolog (也许还有其他)中,这与通过和求值的表达式的向后兼容性实现有关:is/2=:=/2

.(+Int,[])

A list of one element evaluates to the element. This implies "a" evaluates to 
the character code of the letter `a' (97). This option is available for 
compatibility only. It will not work if `style_check(+string)' is active as "a"
will then be transformed into a string object. The recommended way to specify the
character code of the letter `a' is 0'a.
Run Code Online (Sandbox Code Playgroud)

由于字符代码是非负整数,这可以解释为什么您看到的行为仅适用于此类数字,而不适用于浮点数和负数。

  • 该页面是关于 SWI-Prolog 的;也许您的实现不支持最小值、最大值等?一些参数前面有“+”,因为这表示模式,即“+”表示绑定(而不是变量)。最后,列表语法“[a,b]”是“./2”列表构造函数谓词的简写(实际上是“.(a,.(b,[]))”)。在您的情况下,像“[1]”这样的单整数列表是“.(1,[])”的简写。 (2认同)