I'm new to OCaml. I want to define a type that is used in one function only. I don't want to make it available outside that function. Can we define it inside that function? Or is there some other way to achieve the same?
Function Expression Function in ocaml is a expression. That means, a function is a value that represents the function. This is also called anonymous function, lambda. (* syntax for a function expression *) fun n -> n + 1;; (* applying a function to a value *) (fun n -> n + 1) 2;; (* ⇒ 3 *)
OCaml uses this convention to help catch more type errors. Some of the built-in types are not types per se but rather families of types, or compound types, or type constructors. Tuples, lists, arrays, records, functions, objects and variants are of this sort.
ML-derived languages like OCaml are "mostly pure". They allow side-effects through things like references and arrays, but by and large most of the code you'll write will be pure functional because they encourage this thinking.
The type 'a is a type variable, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, <=, etc.) are polymorphic in OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.
If you have recent version of OCaml, you could use a local module:
let f x =
let module Local = struct
type t = A | B
end in
...
It may be more natural to define the type at top level and just leave it out of the .mli
, though: that would keep it globally hidden, although it would be visible to other code in the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With