Sök…


Läs från standardinmatning och skriv ut till standardutdata

Vi förbereder en fil som heter reverser.ml med följande innehåll:

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

Vi sammanställer sedan vårt program med följande kommando:

$ ocamlc -o reverser.byte reverser.ml

Vi testar det genom att leda data till vår nya körbara:

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

Programmet reserver.ml är skriven i en tvingande stil. Medan tvingande stil är bra, är det intressant att jämföra detta med den funktionella översättningen:

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 []

Tack vare introduktionen av funktionen maybe_read_line är kontrollflödet mycket enklare i den andra versionen än i den första.



Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow