[Haskell-beginners] Further constraining types

Christopher Howard christopher.howard at frigidcode.com
Thu Aug 4 07:03:07 CEST 2011


Let's say I have "f", which is a function of the following type:

f :: Int -> Int

However, let's say f is only capable of handling positive integers.
Let's say that I'm committed to making f a complete function in the
sense that (1) the pattern matching of the function is always complete
and (2) there are no internal aborts, like an "error" call or an
"undefined" expression. Obviously I could change the type to

f :: Int -> Maybe Int

...to deal with the case where a negative parameter is passed in. But it
seems like what I really want is something like this:

f :: Positive Int -> Int

I.e., the "positiveness" is hard-coded into the parameter type. But how
do I do this? I was thinking it would involve some kind of "Positive
Int" type, and some kind of "constructor" function like so:

positiveNum :: Int -> Positive Int

However, then this constructor function must deal with the problem of
receiving a negative integer, and thus I have only shifted the problem.
It is still an improvement, but yet it seems like I am missing some
important concept here...

-- 
frigidcode.com
theologia.indicium.us



More information about the Beginners mailing list