OCaml 从标准输入读取并打印到标准输出

示例

我们准备一个包含reverser.ml以下内容的文件:

let acc = ref [] in
    try
        while true do
            acc := read_line () :: !acc;
        done
    with
        End_of_file -> print_string (String.concat "\n" !acc)

然后,我们使用以下命令编译程序:

$ ocamlc -oreverser.bytereverser.ml

我们通过将数据传递到新的可执行文件进行测试:

$ cat data.txt
one
two
three
$ ./reverser.byte < data.txt
three
two
one

该reserver.ml程序以命令式风格编写。虽然命令式样式很好,但是将其与功能翻译进行比较很有趣:

let maybe_read_line () =
  try Some(read_line())
  with End_of_file -> None

let rec loop acc =
  match maybe_read_line () with
  | Some(line) -> loop (line :: acc)
  | None ->List.iterprint_endline acc

let () = loop []

由于引入了该功能maybe_read_line,因此第二个版本中的控制流程比第一个版本简单得多。