How to define a function which takes "nothing" and returns "nothing"

I wanted to explicitly specify input-type and output-type which is “unit”

let myfunction : ()->() = print_int "Hallo" in
let ()= myfunction ()

You’re just missing the input param to your function:

let myfunction () : unit -> unit = print_int "Hallo" in
myfunction ()

Update:
Fixed type thanks to subsequent reply. Funny that I still forget this :slight_smile:

The type is unit -> unit rather than () -> ().

1 Like

Why not let the compiler infer the type? It’s better at that than humans :slightly_smiling_face:

let myfunction () = print_endline "Hallo"
(* compiler infers: val myfunction : unit -> unit *)

Note that unit is the name of the type, () is the value of that type.

3 Likes

This worked,
let myfunction ():(unit->unit) = fun () → print_string “123\n”;;
myfunction () ();;

This also,
let myfunction ():(unit) = print_string “123\n”;;
myfunction ();;

I am missing some basics.
I would be nice to have the ocaml equivalent of C with explicit input & output,

void Write ( void ) {
printf ("Hi there");
}

You have an extra argument if your function that you do not seems to consider in your signature:

is equivalent to

let myfunction: unit -> unit -> unit =  fun () () → …;;

I think what you really want is to remove the () before the function signature

let myfunction: unit -> unit =  fun () → …;;
1 Like

The annotated ocaml is just as explicit as the c in this case.

I recommend taking a look at OCaml - The module system and OCaml - The module system

you’ve got one unit -> too many

that could be the case of learning the right thing at the wrong time. the simpler approach of annotating types inline should be enough for one-off things… instead of defining interfaces

With my new understanding i’m sharing here what does work,

let (_:unit)=
    let myfunction :unit->unit = fun () -> print_string "Hallo" in
    myfunction () in 
    let myfunction2 (_: unit): unit = print_string "Hallo2" in 
    myfunction2 ()

You probably don’t want in after a function call if it’s not being used in a binding? Something like this might be more suitable:

let () =
    let myfunction () = print_string "Hallo" in
    myfunction ();
    let myfunction2 () = print_string "Hallo2" in 
    myfunction2 ()
2 Likes