正如在另一个答案中所提到的,你需要一些更高级的类型系统才能对它进行编码,所以通常实现你想要的方法是为它提供一个"智能构造函数" newtype
,然后不导出构造函数本身,这样人们只能用你想要的属性构造newtype的值:
module Names (runName, name) where import Prelude import Data.Maybe (Maybe(..)) import Data.String (length) newtype Name = Name String -- No way to pattern match when the constructor is not exported, -- so need to provide something to extract the value too runName :: Name -> String runName (Name s) = s name :: String -> Maybe Name name s = if length s > 5 then Just (Name s) else Nothing