[Haskell-beginners] Further constraining types

Arlen Cuss celtic at sairyx.org
Thu Aug 4 09:36:49 CEST 2011


04.08.2011 15:03, Christopher Howard kirjutas:
> 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...

What about positiveNum :: Int -> Maybe (Positive Int)? The reality is
you need to provide a way to get some Int to Positive Int, and since
Haskell doesn't have the notion of a positive-only Int built in, you
need to be prepared that a non-positive Int might get through to your
constructor at runtime.

After that, you're set!




More information about the Beginners mailing list