Search code examples
prologdcg

Prolog DCG is returning a forumla instead of a value


I'm trying to learn how to use DCG and I've run into a problem when the return value I'm getting is the formula instead of the sum of the formula, e.g A = 1+3*20 instead of A = 61. What am I doing wrong? I tried typing dansk(A) --> en2ni(A1), [og], tyve2halvfems(A2), A is A1+A2. to but then I'm getting the error

ERROR: dansk/3: Undefined procedure: (is)/4
ERROR:     However, there are definitions for:
ERROR:         system:is/2

Any ideas what I'm doing wrong?

dansk(A) --> nul(A).
dansk(A) --> en2ni(A).
dansk(A) --> ti2nitten(A).
dansk(A1+A2) --> en2ni(A1), [og], tyve2halvfems(A2).
dansk(A) --> tyve2halvfems(A).

nul(0) --> [nul].

en2ni(1) --> [en].
en2ni(1) --> [et].
en2ni(2) --> [to].
en2ni(3) --> [tre].
en2ni(4) --> [fire].
en2ni(5) --> [fem].
en2ni(6) --> [seks].
en2ni(7) --> [syv].
en2ni(8) --> [otte].
en2ni(9) --> [ni].

ti2nitten(10) --> [ti].
ti2nitten(11) --> [ellve].
ti2nitten(12) --> [tolv].
ti2nitten(13) --> [tretten].
ti2nitten(14) --> [fjorten].
ti2nitten(15) --> [femten].
ti2nitten(16) --> [seksten].
ti2nitten(17) --> [sytten].
ti2nitten(18) --> [atten].
ti2nitten(19) --> [nitten].

tyve2halvfems(20) --> [tyve].
tyve2halvfems(30) --> [tredive].
tyve2halvfems(40) --> [fyrre].
tyve2halvfems(50) --> [fyrretyve].
tyve2halvfems(A1*A2) --> [halv], halvmult(A1), emfas(A2).
tyve2halvfems(A1*A2) --> mult(A1), emfas(A2).

mult(3) --> [tres].
mult(4) --> [firs].
mult(4) --> [fjerds].

halvmult(A-0.5) --> mult(A).
halvmult(4.5) --> [fems].

emfas(20) --> [sindstyve].
emfas(20) --> [].

Solution

  • your DCG builds the expression syntax tree. You can call is/2 on it.

    ?- phrase(dansk(X), [tre,og,fyrre]), Y is X.
    X = 3+40,
    Y = 43 ;
    false.
    

    (note: I have no idea what 'tre,og,fyrre' means :)