I wanted to explicitly specify input-type and output-type which is “unit”
let myfunction : ()->() = print_int "Hallo" in
let ()= myfunction ()
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
The type is unit -> unit
rather than () -> ()
.
Why not let the compiler infer the type? It’s better at that than humans
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.
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 () → …;;
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 ()