Search code examples
prologdcg

How do you translate DCGs into normal definite clauses in PROLOG?


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 .

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...