What's the theoretical basis for existential types?

前端 未结 3 2057
独厮守ぢ
独厮守ぢ 2020-12-22 18:54

The Haskell Wiki does a good job of explaining how to use existential types, but I don\'t quite grok the theory behind them.

Consider this example of an existential

3条回答
  •  情书的邮戳
    2020-12-22 19:38

    It's stated in the haskell wiki article you linked. I'll borrow some lines of code and comments from it and try to explain.

    data T = forall a. MkT a
    

    Here you have a type T with a type constructor MkT :: forall a. a -> T, right? MkT is (roughly) a function, so for every possible type a, the function MkT have type a -> T. So, we agree that by using that constructor we may build values like [MkT 1, MkT 'c', MkT "hello"], all of them of type T.

    foo (MkT x) = ... -- what is the type of x?
    

    But what does happen when you try to extract (e.g. via pattern matching) the value wrapped within a T? Its type annotation only says T, without any reference to the type of the value actually contained in it. We can only agree on the fact that, whatever it is, it will have one (and only one) type; how can we state this in Haskell?

    x :: exists a. a
    

    This simply says that there exists a type a to which x belongs. At this point it should be clear that, by removing the forall a from MkT's definition and by explicitly specifying the type of the wrapped value (that is exists a. a), we are able to achieve the same result.

    data T = MkT (exists a. a)
    

    The bottom line is the same also if you add conditions on implemented typeclasses as in your examples.

提交回复
热议问题