Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1661059
  • 博文数量: 230
  • 博客积分: 10045
  • 博客等级: 上将
  • 技术积分: 3357
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-30 20:40
文章分类

全部博文(230)

文章存档

2011年(7)

2010年(35)

2009年(62)

2008年(126)

我的朋友

分类:

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 ()
}
阅读(1434) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~