在 Prolog 中使用 DCG 搜索列表中的元素

Searching for a element in a List using DCG in Prolog

我有一个列表

[-r,-R,-f,-i,-p]

我的测试用例是使用 DCG

检查元素是否存在于列表中
atom_codes('-R',X), phrase(cp_list(Y),X). 
Y='-R' or the ASCII Code

我已经在 Prolog 中实现了这个

% Use after stripping the '-' symbol from an atom
sub_element([],[]).
sub_element(X,[S|Y]):-
    X = [H|T],
    sub_atom(H, 1, 1, _, S),
    member(S,[r,f,i,p,'R']),
    sub_element(T,Y).

我将如何使用 DCG 实现它。

交互式控制台测试:

?- phrase(("-",("r"|"R"|"f"|"i"|"p")), `-R`).
true 

可重用代码可以是:

?- [user].
flag --> "-", [C], {memberchk(C, `rRfip`)}.

?- phrase(flag, `-R`).
true.

此类代码已通过 SWI-Prolog v.7 测试,请注意带有反引号的代码表示列表。

OT:关于您的 sub_element/2 的评论让我感到困惑:sub_atom(H, 1, 1, _, S) 似乎要求您 不要 去掉破折号...