open Scanf

let skipspace() = scanf "%_[\t\011\012\r ]" ()

let rec factor() =
  skipspace();
  try scanf "(" ();
      let r = expr() in
      skipspace();
      try scanf ")" (); r
      with End_of_file | Scan_failure _ -> failwith "missing )"
  with Scan_failure _ -> scanf "%d" (fun x -> x)(* citeste un intreg *)

and term() =
  let rec term1 t1 =        (* a citit t1, cauta mai departe factor *)
    skipspace();
    try
      try scanf "*" (); term1(t1 * factor())
      with Scan_failure _ -> scanf "/" (); term1(t1 / factor())
    with End_of_file | Scan_failure _ -> t1
  in term1 (factor())        (* citeste termen, pornind de la primul factor *)

and expr() =
  let rec expr1 e1 =        (* a citit e1, cauta mai departe termen *)
    skipspace();
    try 
      try scanf "+" (); expr1 (e1 + term())
      with Scan_failure _ -> scanf "-" (); expr1 (e1 - term())
    with End_of_file | Scan_failure _ -> e1
  in expr1 (term())        (* citeste expresie, pornind de la primul termen *)
;;

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

This document was generated using caml2html