Local type definition

Hello everyone,

As far as I know, there is no way to locally define a type, is there a reason for that? I know you can always create polymorphic variants on the fly, but I feel it might be nice to be able to do that.

Example of application:

type t = | A1 | A2 | A3 | B1 | B2 | B3

let f (x:t): string * int =
  let type radix = | A | B in
  let radix = function
  | A1 | A2 | A3 -> A | _ -> B
  in
  begin match radix with
  | A -> do_something ()
  | B -> do_something_else ()
  end ;
  do_yet_something_else () ;
  begin match radix with
  | A -> return_something
  | B -> return_something_else

Obviously, one can find a lot of alternative ways to solve this. My question is “Why would we not allow that” rather than “How else can we do that”.

Any attempt at an answer appreciated :slight_smile:

Oh yes of course, local modules, I don’t know how I didn’t think about it…

Thank you!

Directly doing let type ... is indeed not possible at the moment, but might be in the future as there is an open PR about this (on which I probably need to spend time to give it more chances of being merged)

2 Likes

Note that such way to define a new local type involves an allocations which can be hard to track (and probably uneeded for the purpose).

No it does not. Perhaps you are confusing this construct with the one used to extend an already existing extensible type (e.g., exceptions)?

That’s indeed true if you don’t define & use functions into this module.