Is this use of GADT completely equivalent to existential types?

Specific quantitative data constructors , for example

data Foo = forall a. MkFoo a (a -> Bool)
         | Nil

can be easily translated to GADT:

data Foo where 
    MkFoo :: a -> (a -> Bool) -> Foo
    Nil :: Foo

Are there differences between the two: code that compiles with one and not the other, or gives different results?

+4
source share
3 answers

They are almost equivalent, although not completely, depending on which extensions you include.

First of all, note that you do not need to include an extension GADTsto use the syntax data .. wherefor existential types. It is enough to include the following smaller extensions.

{-# LANGUAGE GADTSyntax #-}
{-# LANGUAGE ExistentialQuantification #-}

With these extensions you can compile

data U where
    U :: a -> (a -> String) -> U

foo :: U -> String
foo (U x f) = f x

g x = let h y = const y x
      in  (h True, h 'a')

,

{-# LANGUAGE ExistentialQuantification #-}
data U = forall a . U a (a -> String)

GADTs! , GADTs MonoLocalBinds, g. , h .

+9

:

, GADT- ( ). , :

data Foo = forall a. MkFoo a (a -> Bool)
data Foo' where { MKFoo :: a -> (a->Bool) -> Foo' }

( )

+4

GADT - , GADT. , .

, GADT, , , . , GADT. GADT, :

data Foo a where
    StringFoo :: String -> Foo String
    IntFoo :: Int -> Foo Int

, . :

deconstructFoo :: Foo a -> a
deconstructFoo (StringFoo s) = "Hello! " ++ s ++ " is a String!"
deconstructFoo (IntFoo i)    = i * 3 + 1

, - . deconstructFoo promises a, Foo a. a String, Int.

This is something you cannot do with the regular data type, and the new thing provided by GADT. In the first equation, matching a pattern adds a constraint (a ~ String)to its context. In the second equation, pattern matching adds (a ~ Int).

If you have not created a type in which pattern matching can cause a type refinement, you do not have GADT. You just have a type declared with GADT syntax. What's good is, in many ways, this is better syntax than the syntax of the underlying data type. This is just more detailed for the simplest cases.

+4
source

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


All Articles