On Tue, Feb 04, 2025 at 08:25:58AM +0000, Richard W.M. Jones wrote:
unit is a bit like void in C
...
# let f () =
2+5;
() ;;
Warning 10 [non-unit-statement]: this expression should have type unit.
val f : unit -> unit = <fun>
So unit isn't exactly like void in C, although it has similarities.
Functions in OCaml must have at least 1 parameter. If you want to
simulate a function with no parameters, you give them one parameter of
type 'unit'. The 'unit' type is a regular type (like 'int' or
'string'), but it only has a single possible value, written '()'.
Thus 'f ()' means pass the parameter '()' (of type 'unit') to the
function 'f'. It doesn't mean pass zero parameters.
You can if you want (and this is even occasionally useful) have a
function that takes two unit parameters, eg:
# let f () () = () ;;
val f : unit -> unit -> unit = <fun>
or something else and a unit (also occasonally useful):
# let g i () = string_of_int i ;;
val g : int -> unit -> string = <fun>
Similarly, OCaml functions can't return "nothing" (ie. void). They
must return something, but if you don't want them to return anything
you can have them return unit, which means they will return only the
single value '()' (or could throw an exception).
Functions can't return multiple values (unlike in LISP), but they can
return an n-tuple, eg this is unnatural but possible:
# let h () = (), () ;;
val h : unit -> unit * unit = <fun>
HTH,
Rich.
--
Richard Jones, Virtualization Group, Red Hat
http://people.redhat.com/~rjones
Read my programming and virtualization blog:
http://rwmj.wordpress.com
virt-top is 'top' for virtual machines. Tiny program with many
powerful monitoring features, net stats, disk stats, logging, etc.
http://people.redhat.com/~rjones/virt-top