0

I have following type definition of x with a GADT.

type x = X : 'a option -> x

and I'm trying to write a function to get the value of option accompanying with tag X

I first tried the following

let get = fun (X a)->a

and obtained the following error message

Error: This expression has type $X_'a option
       but an expression was expected of type 'a
       The type constructor $X_'a would escape its scope

secondly I tried this

let get : type a.x-> a option =  fun (X a)->a

and following

Error: This expression has type $X_'a option
       but an expression was expected of type a option
       Type $X_'a is not compatible with type a

I think since the type 'a given to the option inside type x doesn't appear in type annotation, there is no way to write what 'a actually is in type annotation explicitly.

glennsl
  • 28,186
  • 12
  • 57
  • 75
mofu
  • 1
  • 1
  • This is succeed.`module M = struct type t type x = X : t option -> x end let get : M.x -> M.t option = fun (M.X a)->a` – mofu Aug 28 '23 at 00:04

1 Answers1

2

You're exactly right. You can't access that type. It's an existential type, which means it can't be recovered. There's no magic trick to reconstruct such a type from a runtime value, as that would require the compiler to know about the runtime value of an expression at compile-time.

Perhaps you meant to include the type 'a as part of the type of x?

type 'a x = X : 'a option -> 'a x

which doesn't require the GADT syntax anymore and can be written more succinctly as

type 'a x = X of 'a option
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • thank you for quick answer. but the code I gave above is simplified version I'm fighting with now which is more larger gadt definiton and more complicated. – mofu Aug 28 '23 at 00:02
  • thank you. your explanation vely helps me. I will use ordinary variant. The code using a module did pass some of code but since they aren't polymorphic, finally fails somewhere. Thank you your answer!! – mofu Aug 28 '23 at 00:20
  • I got it. What I was trying to do was to get the type that is hidden by an existential type, which is impossible. – mofu Aug 28 '23 at 00:34
  • Exactly! If you need access to the type, you have to keep track of it somewhere. Existentials eliminate that information, and there's no way to recover it once it's gone. – Silvio Mayolo Aug 28 '23 at 00:36