typesocaml

Why does the OCaml function `read_line` have type `unit -> string`?


I understand that its return type is the string that is read but why does it need the parameter of type unit?


Solution

  • Every OCaml function takes one value and returns one value. Since there are no meaningful values that read_line could take but it must take something, unit is provided.

    And read_line must be a function, because some work has to be done when it's called.

    Likewise, a function which performs an action but for which there is no meaningful return value typically returns unit in OCaml.

    E.g.

    # print_endline "Hello, world!";;
    Hello, world!
    - : unit = ()