Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we define types inside a function in OCaml?

Tags:

ocaml

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?

like image 735
Manjeet Dahiya Avatar asked Nov 07 '13 07:11

Manjeet Dahiya


People also ask

How do you define a function in OCaml?

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 *)

Does OCaml have types?

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.

Is OCaml purely functional?

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.

What is type A in OCaml?

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.


1 Answers

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.

like image 79
gsg Avatar answered Oct 22 '22 20:10

gsg