Haskell Structures and Conditional Data

Is it possible to write something like:

data SomeData = SomeValue | (Integral a) => SomeConstructor a

And how exactly to write it?

+3
source share
4 answers

This is similar to Daniel Pratt's answer, but a more typical approach is to discard the type constraints in the data definition, for example:

data SomeData a = SomeValue
                | SomeConstructor a

(Integral a) , , . , SomeData, , , a . . 10 Real World Haskell.

+12

, GADT:

{-# LANGUAGE GADTs #-}
data SomeData
    where
    SomeValue :: SomeData
    SomeConstructor :: Integral a => a -> SomeData

:

*Main> :t SomeValue 
SomeValue :: SomeData

*Main> :t SomeConstructor 15
SomeConstructor 15 :: SomeData

*Main> :t SomeConstructor "aaa"

<interactive>:1:0:
    No instance for (Integral [Char])
      arising from a use of `SomeConstructor' at <interactive>:1:0-20
    Possible fix: add an instance declaration for (Integral [Char])
    In the expression: SomeConstructor "aaa"

*Main> let x = SomeConstructor 15 in case x of { SomeConstructor p -> fromIntegral p :: Int }
15
+6

Yes, exactly as you want, but you need to specify a quantitative assessment:

{-# LANGUAGE ExistentialQuantification #-}

data SomeData = SomeValue
              | forall a . Integral a => SomeConstructor a
+2
source

You can do something like this:

data Integral a => SomeData a =
    SomeValue
    | SomeConstructor a
0
source

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


All Articles