Existential types. Class instance record for a heterogeneous map

Using the following definitions of types and classes, I do not understand why I get an error when creating an instance below.

I need MyMap to hold a map of heterogeneous values.

 {-# LANGUAGE ExistentialQuantification #-} module Scratch.SO_ExtistentialTypes where import Data.Map type MyMap a = Map String a class MyClass c where getMyMap :: forall a. c -> MyMap a data MyData = forall a. MyData { myMap :: MyMap a } instance MyClass MyData where getMyMap = myMap -- <= ERROR 
+1
source share
1 answer

On the one hand, forall is superfluous here:

 class MyClass c where getMyMap :: forall a. c -> MyMap a 

Sample variables without explicit binding are universally evaluated at the most remote level, so this is exactly the same as c -> MyMap a .

In addition, the universally quantified type, of course, will not correspond to the existentially quantized type. The getMyMap type indicates that with a value of type c it MyMap a value of type MyMap a for any possible choice of type a . On the other hand, the accessor myMap says that with a value of type MyData it will MyMap a value of type MyMap a for a specific but unknown type a .

It is not possible to expand pop-up types of existential types (this requires a quantifier corresponding to forall ), so there is no way to rewrite the type getMyMap so that myMap a valid implementation.

All that you can do with something of an existential type completes its backup in another data type, which hides the existential quantifier, or passes it to a function that has an argument with a universal quantized type. For example, you can use length in list [a] with a existential type.

In your case, Map values ​​are existential type without any other structure or restrictions, so they are practically useless and can also be () .

+9
source

Source: https://habr.com/ru/post/1442447/


All Articles