Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

ksson

By: a guest on Jun 19th, 2009  |  syntax: OCaml  |  size: 0.75 KB  |  views: 197  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. {
  2. type expr =
  3.   | Op of (float -> float -> float)
  4.   | Const of float
  5.   | NL
  6. }
  7.  
  8. let digit = ['0'-'9']
  9. let float = digit+ ('.' digit+)?
  10.  
  11. rule token = parse
  12. | [ ' ' '\t' ] { token lexbuf }
  13. | float as f { let f = float_of_string f in Const f }
  14. | '+' { Op (+.) }
  15. | '/' { Op (/.)  }
  16. | '-' { Op (-.) }
  17. | '*' { Op ( *. ) }
  18. | '\n' { NL }
  19. | eof { exit 0 }
  20. | _ as c { failwith (Printf.sprintf "invalid char: %c\n" c) }
  21.  
  22. {
  23. let main =
  24.   let lexbuf = Lexing.from_channel stdin in
  25.   let rec aux stack =
  26.     match token lexbuf with
  27.     | Const f -> aux (f::stack)
  28.     | NL -> Format.printf "%f@." (List.hd stack); aux stack
  29.     | Op f ->
  30.         match stack with
  31.         | x :: y :: r -> aux ( f y x :: r)
  32.         | _ -> assert false
  33.   in
  34.   aux []
  35. }