Search code examples
ocamlyaccocamlyacc

if then else in ocamlyacc


Can anyone brief how can I implement if then else in Ocamlyacc. I've defined tokens from lexical analyzer(ocamllex) namely IF, THEN, ELSE. For the if statement, I have defined tokens: GREATERTHAN, LESSERTHAN, EQUALTO for integers. I've searched many tutorials but to no avail!

UPDATE:

I want to interpret the result and return the value of the expression dictated by the if-else statement.


Solution

  • You have to define rules :

    ifthenelse :    
     |   IF condition THEN statement ELSE statement   { IfThenElse($1,$2,$3) }
    
    
    condition :    
    | INT EQUALTO INT  { Cond(EqualTo,$1,$3) }   
    | INT LESSERTHAN INT {  Cond(LesserThan,$1,$3) }   
    | INT GREATERTHAN INT {  Cond(GeaterThan,$1,$3) }
    

    Don't forget to define regular expression for int, in your lex fil