home *** CD-ROM | disk | FTP | other *** search
/ Garbo / Garbo.cdr / mac / progrmng / cmlmcmpw.sit / Caml Light / examples / wc.ml < prev   
Encoding:
Text File  |  1991-05-23  |  1.1 KB  |  47 lines  |  [TEXT/MPS ]

  1. (* Counts characters, lines and words in one or several files. *)
  2.  
  3. let chars = ref 0
  4. and words = ref 0
  5. and lines = ref 0
  6. ;;
  7.  
  8. type state = Inside_word | Outside_word;;
  9.  
  10. let count_channel in_channel =
  11.   let rec count status =
  12.     let c = input_char in_channel in
  13.     incr chars;
  14.     match c with
  15.       `\n` ->
  16.         incr lines; count Outside_word
  17.     | ` ` | `\t` ->
  18.         count Outside_word
  19.     | _ ->
  20.         if status = Outside_word then begin incr words; () end;
  21.         count Inside_word
  22.   in
  23.     try
  24.       count Outside_word
  25.     with End_of_file ->
  26.       ()
  27. ;;
  28.  
  29. try
  30.   if vect_length unix__command_line <= 1 then
  31.     count_channel std_in                (* No command-line arguments *)
  32.   else
  33.     for i = 1 to vect_length unix__command_line - 1 do
  34.       let ic = open_in unix__command_line.(i) in
  35.         count_channel ic;
  36.         close_in ic
  37.     done;
  38.   print_int !chars; print_string " characters, ";
  39.   print_int !words; print_string " words, ";
  40.   print_int !lines; print_string " lines\n";
  41.   exit 0
  42. with unix__OS_error n ->
  43.   print_string "I/O error: "; print_string (unix__os_error_message n);
  44.   print_newline();
  45.   exit 1
  46. ;;
  47.