Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Trouble defining a grammar in Prolog

Name: GregorianChantChan 2013-07-22 8:36

I want to generate algebraic expressions. Every expression generated should have precisely four unique variables. Pairs of variables are operated on by the operators +, -, /, * and ^. Subexpressions should be enclosed by parentheses to avoid ambiguity.
 
Expressions in the desired grammar:
>((b^(a/c))-d)
>((d*(b-a))*c)
>(((b/d)/c)/a)
>(c*((a+b)/d))

Expressions not in the desired grammar:
>((b/c)/a) [only contains three variables]
>(c*((a+b)/a)) [the variable, a, appears more than once]
>b^a/c-d [missing brackets]
>((b^a/c)-d) [missing brackets around the exponent, a/c]

I'm using the SWI flavour of Prolog.



    % EQUATION GRAMMAR
    expr --> expr(4).
    expr(1) --> term.
    expr(N) --> bracketLeft, expr(N1), spacedOp, expr(N2), bracketRight, {N is N1 + N2}.
    term --> [a].
    term --> [b].
    term --> [c].
    term --> [d].
    spacedOp --> space, operator, space.
    operator --> [+].
    operator --> [-].
    operator --> [*].
    operator --> [/].
    operator --> [^].
    space --> [' '].
    bracketLeft --> ['('].
    bracketRight --> [')'].

Name: Anonymous 2013-07-22 8:37

Why not solve this problem generally? Or must you do error-checking on the input?

Name: Anonymous 2013-07-22 8:44

>>2
What do you mean, solve it generally? What problem do you think I'm trying to solve?

Don't change these.
Name: Email:
Entire Thread Thread List