'OCaml explicit type signatures
In Haskell, it is considered good practice to explicitly declare the type signature of your functions, even though it can (usually) be inferred. It seems like this isn't even possible in OCaml, e.g.
val add : int -> int -> int ;;
gives me an error. (Although I can make type
modules which give only signatures.)
- Am I correct in that this isn't possible to do in OCaml?
- If so, why? The type system of OCaml doesn't seem that incredibly different from Haskell.
Solution 1:[1]
OCaml has two ways of specifying types, they can be done inline:
let intEq (x : int) (y : int) : bool = ...
or they can be placed in an interface file, as you have done:
val intEq : int -> int -> bool
I believe the latter is preferred, since it more cleanly separates the specification (type) from the implementation (code).
References: OCaml for Haskellers
Solution 2:[2]
In general, the syntax to let
-bind a value with a constrained type is:
let identifier_or_pattern : constraint = e ...
Applied to a function, you can specify the signature as follows:
let add : int -> int -> int = fun x y -> ...
This is analogous to the syntax required to constrain a module to a signature:
module Mod
: sig ... end
= struct ... end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Don Stewart |
Solution 2 | glennsl |