Advanced Functional Prog.

back - up - cont


Parsing expressions

Now, the parser can be adapted to return an abstract syntax tree (rather than a value):

type Exp = Val of int | Plus of Exp*Exp | Mult of Exp*Exp;;

let rec exp = 
  (((num' && fun n -> ret (Val n)) 
   || 
   (sym '('   && fun _  -> 
    exp       && fun e  -> 
    sym ')'   && fun _  -> 
    ret e))   && fun e1 -> 
   ((sym '+') && fun _  -> 
    exp       && fun n2 -> 
    ret (Plus (e1,n2))) 
   || 
   ((sym '*') && fun _  -> 
    exp       && fun n2 -> 
    ret (Mult (e1,n2))) 
   || 
   ret e1);;

exp "(12+34)*56";;

17 - 18