open Scanf

(* "%0c" obtine caracterul fara sa-l consume; "%_c" citeste si ignora *)
let rec expr() =
  let factor () = 
    try scanf " %0c" (function
    | '(' -> scanf "%_c" ();
      let e = expr() in (
        try scanf " )" (); e
        with Scan_failure _ | End_of_file -> failwith "missing )"
      )
    | _ -> scanf " %d" (fun n -> n))
    with Scan_failure _ | End_of_file -> failwith "number or ( expected"
  in let term() =
       let rec term1 t =
         try scanf " %0c" (function 
         | '*' -> scanf "%_c" (); term1(t * factor())
         | '/' -> scanf "%_c" (); term1(t / factor()))
         with Scan_failure _ | End_of_file -> t
  in term1 (factor())
     in let rec expr1 e =
          try    scanf " %0c" (function 
          | '+' -> scanf "%_c" (); expr1(e + term())
          | '-' -> scanf "%_c" (); expr1(e - term()))
          with Scan_failure _ | End_of_file -> e
        in expr1 (term())
        
let _ = print_int(expr())

This document was generated using caml2html