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,因此第二个版本中的控制流程比第一个版本简单得多。
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短