Haskell中的约束值类型

时间:2017-01-04 14:23:21

标签: haskell types functional-programming immutability value-type

是否可以在Haskell中定义约束类型,即我希望能够表达,

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

作为一种类型,如果可能的话。

1 个答案:

答案 0 :(得分:14)

可以在现代GHC中完成(> = 7.10,可能已经是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")
Nothing

我认为在GHC-8中,您甚至可以legalSet StringKnownSymbol并取消import sys def print_message(): print "You pressed the `Enter` key!" 约束,但不确定它是如何工作的。