Question: Constrained Value Types in Haskell


Constrained Value Types in Haskell

Answers 1
Added at 2017-01-04 15:01

Is it possible to define constrained types in Haskell, i.e. I would like to be able to express,

Prelude> let legalCharacters = ' ':['A'..'Z']
Prelude> legalCharacters

as a type, if possible.

Answers to

Constrained Value Types in Haskell

nr: #1 dodano: 2017-01-04 15:01

Can be done in modern GHC (>= 7.10, perhaps already 7.8).

{-# LANGUAGE KindSignatures, DataKinds, MonoLocalBinds #-}
import GHC.TypeLits

newtype LegalChar (legalSet :: Symbol)
   = LegalChar {getLegalChar :: Char}
  deriving (Show)

fromChar :: KnownSymbol legal => Char -> Maybe (LegalChar legal)
fromChar c
   | c`elem`symbolVal r = Just r
   | otherwise          = Nothing
 where r = LegalChar c


*Main> fromChar 'a' :: Maybe (LegalChar "abc")
Just (LegalChar {getLegalChar = 'a'})
*Main> fromChar 'x' :: Maybe (LegalChar "abc")

I think in GHC-8 you can even give legalSet the kind String and do away with the KnownSymbol constraint, not sure how that would work.

Source Show
◀ Wstecz