Question

How would you translate the following DCGs into normal definite clauses of PROLOG?

expr_regular --> cor_ini,numero,guion,numero,cor_fin.
cor_ini --> ['['].
numero --> ['0'];['1'];['2'];['3'];['4'];['5'];['6'];['7'];['8'];['9'].
cor_fin --> [']'].
guion --> ['-'].

EDIT: I want to translate the DCG into normal PROLOG clauses cause I can't use both DCGs and normal clauses in the same code(in my case). I have this two pieces of code:

Piece1:

traducir(Xs, Ys) :- maplist(traduccion, Xs, Ys).
traduccion('^',comeza_por).
traduccion('[',inicio_rango).
traduccion('0',cero).
traduccion('-',a).
traduccion('9',nove).
traduccion(']',fin_rango).

An example of how to use it would be:

?- traducir(['[','0','-','9',']'],[]).
true .

And Piece2:

 traducir--> cor_ini,numero,guion,numero,cor_fin.
 cor_ini --> ['['].
 numero --> ['0'];['1'];['2'];['3'];['4'];['5'];['6'];['7'];['8'];['9'].
 cor_fin --> [']'].
 guion --> ['-'].

An example of how to use it would be:

traducir(['^','[','0','-','9',']'],X).
X = [comeza_por, inicio_rango, cero, a, nove, fin_rango].

I want to join both codes into one to test if traducir is well written (if it follows the DCG) and to translate what you enter into text ,so the final program should able to do the following:

?- traducir(['^','[','0','-','9',']'],X).
X = [comeza_por, inicio_rango, cero, a, nove, fin_rango].
?- traducir(['[','0','-','9',']'],[]).
true .
Was it helpful?

Solution

Your grammar it's exceptionally simple: just terminals. So we can translate to a very specific pattern (beware: no generalization allowed).

expr_regular(S, G) :-
    S = [0'[, N1, 0'-, N2, 0']|G], numero(N1), numero(N2).
numero(N) :-
    memberchk(N, "0123456789").

The only think worth to note it's ISO standard character notation...

OTHER TIPS

In SWI-Prolog you can use listing/1 directly on the :

?- forall(member(NT,[expr_regular//0,cor_ini//0,numero//0,cor_fin//0,guion//0]),
          listing(NT)).
expr_regular(A, F) :-
    cor_ini(A, B),
    numero(B, C),
    guion(C, D),
    numero(D, E),
    cor_fin(E, F).

cor_ini(['['|A], A).

numero(A, B) :-
    (   A=['0'|B]
    ;   A=['1'|B]
    ;   A=['2'|B]
    ;   A=['3'|B]
    ;   A=['4'|B]
    ;   A=['5'|B]
    ;   A=['6'|B]
    ;   A=['7'|B]
    ;   A=['8'|B]
    ;   A=['9'|B]
    ).

cor_fin([']'|A], A).

guion([-|A], A).

true.

That's it! You may profit from looking at the answers of the related question "Is there a way or an algorithm to convert DCG into normal definite clauses in Prolog?".

Well I don't really get your question. Anyway, if you don't want to use the nice DCGs syntax for some reason you can still go with things like wildcard_match/2, or reinvent the wheel and use difference lists yourself to re-implement DCGs, or append. For the wildcard_match/2 part:

expr_regular(R) :- wildcard_match('[[][0-9]-[0-9]]', R).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top