1

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.

user2352241
  • 81
  • 1
  • 9

2 Answers2

3

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

Ontologiae
  • 595
  • 4
  • 11
0

Perhaps you've seen it, but the OCaml manual gives a complete ocamllex/ocamlyacc example that calculates the values of expressions: Desk Calculator Example.

The example shows that you can calculate your result in the ocamlyacc actions if you want to. For a simple example, it's not at all hard to follow. In a more realistic case, you would probably want to construct an abstract syntax tree for later processing (such as evaluation). The code has a similar flavor except that the cases are given by the different constructors of your AST type rather than by the different grammar rules.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108