I am evaluating a very simple piece of code in Ocaml toplevel:
let p5 () = print_int 5;;
p5 ();;
print_string "*************************";;
let p4 = print_int 4;;
p4;;
And it returns:
val p5 : unit -> unit = <fun>
# 5- : unit = ()
# *************************- : unit = ()
# 4val p4 : unit = ()
# - : unit = ()
My questions are
- What does
()mean inlet p5 () = print_int 5;;? - What do
-and()mean in# 5- : unit = ()? - Is
p4a function? - Why is there a
4in the beginning of# 4val p4 : unit = ()? - It seems that
()could be used in Ocaml code to hide side effect, could anyone show me an example?
Here some answers:
()is the unit type value. The unit type is a type with only one value. This is usually used to produce functions which either return nothing meaningful or take nothing meaningful. Remember, that in OCaml all functions alway have to return something and take some arguments, so the unit type is used to get around this limitation. Think of this similar to thevoidtype in C, C++ or Java.5is printed by theprint_intfunction and not by the toplevel. The toplevel just returns- : unit = ()without the5. The toplevel is telling you that it did not create any new bindings-and that the last returned value is of typeunitand has the value().4is printed by theprint_intfunction. At this time, the toplevel is telling you, that it created a new bindingp4, that this variable carries a value of typeunitand that the stored value is().()is not used to hide side effects. It is usually used to create functions, which have side effects, and thus need not take any kind of argument.