open Scanf
let scantest fmt v = scanf fmt ((=) v)  (* citeste si testeaza = v *)

let rec factor() =
  if scantest " %1[(]" "(" then (* un caracter, paranteza ( *)
    let r = expr() in
    if scantest " %1[)]" ")" then r     (* ) inchisa corect *)
    else failwith "missing )"   (* genereaza exceptie cu mesajul dat *)
  else scanf " %d" (fun x -> x)         (* citeste un intreg *)

and term() =
  let rec restterm t1 = (* a citit t1, cauta mai departe factor *)
    if scantest " %1[*]" "*" then restterm (t1 * factor())
    else if scantest " %1[/]" "/" then restterm (t1 / factor())
    else t1             (* nici * nici /, returneaza termenul acumulat *)
  in restterm (factor())(* citeste termen, pornind de la primul factor *)

and expr() =
  let rec restexpr e1 = (* a citit e1, cauta mai departe termen *)
    if scantest " %1[+]" "+" then restexpr (e1 + term())
    else if scantest " %1[-]" "-" then restexpr (e1 - term())
    else e1             (* nici + nici -, returneaza expresia acumulata *)
  in restexpr (term())  (* citeste expresie, pornind de la primul termen *)
;;

(* citirea se termina la EOF *)
print_int(expr()); print_newline()

This document was generated using caml2html