Say i have a function prototype as follows:
func :: [Int] -> [Int]
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
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.
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.
Alternatively, you can use Data.Word.
Have you tried http://hackage.haskell.org/package/non-negative ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With