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 -o reverser.byte reverser.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.iter print_endline acc
let () = loop []
maybe_read_line 함수를 도입 한 덕분에이 두 번째 버전에서는 제어 흐름이 첫 번째 버전보다 훨씬 간단합니다.
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow