假设我有一个函数原型如下:
func :: [Int] -> [Int]
Run Code Online (Sandbox Code Playgroud)
如何仅将非负的整数列表强制实施为输入参数?我必须将[Int]的param类型改为什么..?在这个公平的时刻它与func [-1,-2]一起工作,我只希望它与[1,2]一起工作,即解释器喷出错误信息.
小智 7
newtype NonNegative a = NonNegative a
toNonNegative :: (Num a, Ord a) => a -> NonNegative a
toNonNegative x
| x < 0 = error "Only non-negative values are allowed."
| otherwise = NonNegative x
fromNonNegative :: NonNegative a -> a
fromNonNegative (NonNegative x) = x
Run Code Online (Sandbox Code Playgroud)
请注意不要直接使用NonNegative构造函数.如果将其放在单独的模块中并且不导出它,这将更容易.
此外,现在您可以使用(map toNonNegative)懒惰地转换数字列表.
无论您何时注入原始数字,都仍需要运行时检查.
或者,您可以使用Data.Word.