是否可以在Haskell中定义约束类型,即我希望能够表达,
Prelude> let legalCharacters = ' ':['A'..'Z']
Prelude> legalCharacters
" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
作为一种类型,如果可能的话。
答案 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
String
类KnownSymbol
并取消import sys
def print_message():
print "You pressed the `Enter` key!"
约束,但不确定它是如何工作的。