Home > other >  in OCaml, what's "parenthesis type" as in (type v) in a definition or in a function s
in OCaml, what's "parenthesis type" as in (type v) in a definition or in a function s

Time:01-28

I know generic types, but sometimes I see let a (type v w) etc. in code, what's the difference?

CodePudding user response:

They are locally abstract types. See https://ocaml.org/manual/locallyabstract.html. They are useful for:

  • creating local modules
let sort_and_deduplicate (type a) compare l =
  let module S = Set.Make(struct type t = a let compare = compare end) in
  S.elements (S.of_list l)
  • refining types on pattern matching in presence of GADT
type _ monoid = Int: int monoid | Float: float monoid
let zero (type a) (m:a monoid): a =  match m with
| Int -> 0
| Float -> 0.
  • debugging polymorphic functions
let wrong_id (type a) (x:a) = x   1
Error: This expression has type a but an expression was expected of type int
  •  Tags:  
  • Related