Search code examples
prologswi-prologdcg

Searching for a element in a List using DCG in Prolog


I have a list

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

My test case is to check if the element is present in the List using DCG

atom_codes('-R',X), phrase(cp_list(Y),X). 
Y='-R' or the ASCII Code

I have implement this in 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).

How would i implement this using DCG.


Solution

  • interactive console test:

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

    while reusable code could be:

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

    Such code is tested with SWI-Prolog v.7, beware to list of codes representation with backticks.

    OT: I'm perplexed by the comment about your sub_element/2: sub_atom(H, 1, 1, _, S) seems to require you don't strip the dash...