Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-negative integers [duplicate]

Tags:

types

haskell

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.

like image 203
oem Avatar asked Jan 15 '10 11:01

oem


2 Answers

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.

like image 69
Dagititis Avatar answered Sep 30 '22 14:09

Dagititis


Have you tried http://hackage.haskell.org/package/non-negative ?

like image 38
kennytm Avatar answered Sep 30 '22 15:09

kennytm