代码之家  ›  专栏  ›  技术社区  ›  Vivin Paliath

为什么swi prolog将带引号和不带引号的字符串(不带空格)统一为同一规则?

  •  5
  • Vivin Paliath  · 技术社区  · 14 年前

    假设我有以下规则:

    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', 'this is a test'). ?我是在回答序言问题的时候遇到这个问题的。当我能够回答这个人的问题时,我无法解释这种特殊的行为,我想知道是否还有其他人可以。

    2 回复  |  直到 14 年前
        1
  •  5
  •   sharky    14 年前

    而swi-prolog中的原子可以用单引号表示,例如, 'This is an atom' ,单引号是 不需要 当swi-prolog解析器可以从字符序列中识别原子时,通常以小写字母字符开始,例如 test . 如果序列包含空白(或其他一些字符),则需要单引号来正确地表示原子。字母数字字符和某些标点符号,如下划线 _ 很好,例如, test5_6 .

    如果没有单引号的字符序列以其他任何字符开头,例如数字 6k ,解析器将其视为 number ;如果它是大写字母字符,例如 Test 解析器将把它当作一个变量来处理。

        2
  •  4
  •   false    12 年前

    这不是特定于SWI的行为-这是标准要求的。 有一个简单的方法可以看到这一点。你也可以用这个 语法不明显的任何其他术语。在顶层键入:

    ?- X = 'test'.
    X = test.
    
    ?- X = 'this is a test'.
    X = 'this is a test'.
    

    答案总是有效的prolog文本-这是特定于swi的,但是 也适用于许多其他prolog系统,如yap、gnu、b、if、sicstus。

    另一种方法是使用write_canonical/1:

    ?- write_canonical('this is a test').
    'this is a test'
    true.
    
    ?- write_canonical([a,b,(c,d),{e,f}]).
    '.'(a,'.'(b,'.'(','(c,d),'.'({}(','(e,f)),[]))))
    
    推荐文章