全部博文(230)
分类:
2008-07-17 17:55:16
(*
line counter in OCaml.
Jun 17, 2008
command to build this program:
ocamllex count.mll
ocamlc count.ml -o count.exe
command to test this program:
count < count.mll
*)
{
let num_lines = ref 0
let num_chars = ref 0
}
rule count = parse
| '\n' { incr num_lines; incr num_chars; count lexbuf }
| _ { incr num_chars; count lexbuf }
| eof { () }
{
(* Lexing: The run-time library for lexers generated by ocamllex.
val from_channel : in_channel -> lexbuf
Lexing.from_channel: Create a lexer buffer on the given input channel. Lexing.from_channel
inchan returns a lexer buffer which reads from the input channel inchan,
at the current reading position.
*)
let main () =
let lexbuf = Lexing.from_channel stdin in
count lexbuf;
Printf.printf "# of lines = %d, # of chars = %d\n" (!num_lines + 1) !num_chars
(*
Printexc.print: val print : ('a -> 'b) -> 'a -> 'b
Printexc.print fn x applies fn to x and returns the result. If the
evaluation of fn x raises any exception, the name of the exception
is printed on standard error output, and the exception is raised again.
The typical use is to catch and report exceptions that escape a function
application.
*)
let _ = Printexc.print main ()
}