(* Wc *) (* $Id: wc.ml,v 1.1 2003/01/12 15:33:00 berke Exp $ *) (* By Berke Durak *) let char_stream_to_word_stream s = let b = Buffer.create 16 in let rec state0 = parser [< 'c; s >] -> (match c with (' '|'\n'|'\t') -> state0 s | _ -> Buffer.add_char b c; state1 s) | [< >] -> [< >] and state1 = parser [< 'c; s >] -> (match c with (' '|'\n'|'\t') -> let w = Buffer.contents b in Buffer.clear b; [< 'w; state0 s >] | _ -> Buffer.add_char b c; state1 s) | [< >] -> [< '(Buffer.contents b) >] in state0 s let count_stream = let rec loop i = parser [< 'x; s >] -> loop (i + 1) s | [< >] -> i in loop 0 let _ = Printf.printf "%d\n" (count_stream (char_stream_to_word_stream (Stream.of_channel stdin)))