【问题标题】:Prolog DCG for parsing escaped sequencesProlog DCG 用于解析转义序列
【发布时间】:2014-09-02 22:20:09
【问题描述】:

我需要将字符串^borrow$ ^\$500$ 解析到列表[borrow, $500] 中。我目前写的语法是

:- use_module(library(dcg/basics)).

write_list([]).
write_list([H|T]) :- atom_codes(S, H), write(S), nl, write_list(T).

% Grammar.
tags([Tag|Rest]) --> string(_), tag(Tag), tags(Rest).
tags([]) --> string(_).
tag(Tag) --> "^", tag_contents(Tag), "$".
tag_contents(Tag) --> string(Tag).

当我在令牌中没有\$ 时有效:

?- phrase(tags(T), "^pisica$ ^catel$"), write_list(T).
pisica
catel
?- phrase(tags(T), "^borrow$ ^\\$500$"), write_list(T).
borrow
\

用 Prolog DCG 解析这种转义序列的最佳做法是什么?

【问题讨论】:

    标签: parsing prolog swi-prolog dcg


    【解决方案1】:

    问题是 tag_contents//1 只捕获反斜杠,然后 $ 在父调用中充当标记停止。

    这是一个针对这个问题的丑陋破解:

    tag(Tag1) -->
       "^", tag_contents(Tag), [C], "$", {C \= 0'\\, append(Tag, [C], Tag1) }.
    

    编辑

    一个更好的:

    tag(Tag) --> "^", tag_contents(Tag), "$", {\+last(Tag, 0'\\)}.
    

    编辑

    “最佳实践”当然是使用上下文规则处理嵌套内容。你需要更多的代码...

    tag(Tag) --> "^", tag_contents(Tag).
    
    tag_contents([0'\\,C|Cs]) --> "\\", [C], !, tag_contents(Cs).
    tag_contents([]) --> "$".
    tag_contents([C|Cs]) --> [C], tag_contents(Cs).
    

    【讨论】:

    • 很抱歉破坏了这个,但是使用 tag//1 的 tags//1 是不正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多