【问题标题】:How do I assert a DCG rule in Prolog?如何在 Prolog 中断言 DCG 规则?
【发布时间】:2016-12-13 17:47:01
【问题描述】:

以下 Prolog 为目标 test1test2 打印 done,但不是 test3。我的理解是这段代码中的match_test2match_test3 应该是等价的。如何通过断言创建 DCG 规则?

setup(['t','e','s','t']).

match_test1 --> ['t','e','s','t'].
test1 :-
    setup(C),
    phrase(match_test1,C),
    write("done").

test2 :-
    setup(C),
    assert(match_test2(['t','e','s','t'],[])),
    phrase(match_test2,C),
    write("done").

test3 :-
    setup(C),
    assert(match_test3 --> ['t','e','s','t']),
    phrase(match_test3,C),
    write("done").

使用适用于 x86_64-darwin14.3.0 的 SWI-Prolog 版本 7.2.3,以 swipl -l bug.pl -t test1(或 test2test3)运行

【问题讨论】:

    标签: prolog dcg


    【解决方案1】:

    首先使用expand_term/2将DCG翻译为正则子句:

    ?- expand_term(match_test1 --> [t,e,s,t], 子句)。 子句 = (match_test1([t, e, s, t|_1498], _1498):-true)

    然后像往常一样在Clause 上使用assertz/1,即assertz(Clause)

    请注意,您可以直接写下原子,即不用'e',而只需写下e

    此外,考虑通过添加指令将double_quotes 设置为chars

    :- set_prolog_flag(double_quotes, chars)

    现在你可以写了,非常方便:

    ?- T =“测试”。 T = [t, e, s, t]

    这种语法非常好,让 DCG 更容易调试和使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多