非负整数 [英] Non-negative integers
问题描述
说我有一个函数原型,如下:
Say i have a function prototype as follows:
func :: [Int] -> [Int]
如何仅强制将非负整数列表作为输入参数?我必须将参数类型从[Int]更改为什么.在这个公平的时刻,它可以与func [-1,-2]一起使用,我只希望它与[1,2]一起使用,即由解释器发出错误消息.
How is it possible to enforce only a non-negative list of integers as input arguments? I would have to change the param type from [Int] to what.. ? At this fair moment it works with func [-1,-2], i only want it to work with [1,2] i.e. with the interpreter spewing the error message.
推荐答案
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
请小心不要直接使用NonNegative构造函数.如果将其放在单独的模块中并且不导出,则将更加容易.
Just be careful to never use the NonNegative constructor directly. This will be easier if you put this in a separate module and don't export it.
此外,现在您可以使用(映射到NonNegative)来懒惰地变换数字列表.
Also, now you can use (map toNonNegative) to lazily transform a list of numbers.
无论您在何处注入原始数字,这仍然需要运行时检查.
This will still require a runtime check wherever you inject raw numbers.
或者,您可以使用Data.Word.
Alternatively, you can use Data.Word.
这篇关于非负整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!