nqe
nqe

Reputation: 355

OCaml: Set function signature to that of another function

Let's say I have an on_event function that accepts a handler function that is called when the event occurs. Now I want to write several different event handler functions that I can pass into that on_event function. Is it possible to specify a signature type in the on_event file which I can then set as the signature (in the mli files) of these other functions? This way if I need to change the signature, I'll only need to do it in one place.

Upvotes: 0

Views: 317

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

You can give a name to a type:

type handler = int -> unit

If you put this definition into a module named event.ml, then other modules can name the type as Event.handler.

Note that OCaml will infer types in almost all cases. You don't usually need to specify types for functions. But it's good as documentation.

Update

Here's one way to specify the type of a function when defining it:

let (f: handler) = fun n -> Printf.printf "%d\n" n

Upvotes: 2

Related Questions