Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrained Value Types in Haskell

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
" ABCDEFGHIJKLMNOPQRSTUVWXYZ"

as a type, if possible.

like image 283
Filip Allberg Avatar asked Jan 04 '17 14:01

Filip Allberg


People also ask

What is a type constraint Haskell?

Type constraints (Num a) => is a type constraint, which restricts the type a to instances of the class Num .

What are type constructors in Haskell?

In a data declaration, a type constructor is the thing on the left hand side of the equals sign. The data constructor(s) are the things on the right hand side of the equals sign. You use type constructors where a type is expected, and you use data constructors where a value is expected.


1 Answers

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

Then

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

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.

like image 153
leftaroundabout Avatar answered Nov 03 '22 00:11

leftaroundabout