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 好听的元旦简短祝福语