[Haskell-beginners] Further constraining types

David Virebayre dav.vire+haskell at gmail.com
Fri Aug 5 09:17:22 CEST 2011


2011/8/5 Christopher Howard <christopher.howard at frigidcode.com>:

> But users are not the only source of ints. For example, let's say I wanted
> to do my own square function, with a type like so:

> square :: Int -> Positive Int
> validatePositive :: Int -> Maybe (Positive Int)

> But this means the type of square would have to be changed to
> square :: Int -> Maybe (Positive Int)

I would go with :
 validatePositive :: Int -> Maybe (Positive Int)
 square :: Positive Int -> Positive Int

For the subtraction problem as shown by Thomas, you can
 subtract :: Positive Int -> Positive Int -> Maybe (Positive Int)
 subtract (Positive a) (Positive b)
   | a >= b    = Just $ Positive (a-b)
   | otherwise = Nothing
But that's what you want to avoid, so maybe it's acceptable, depending
on your problem, to do:
 subtract :: Positive Int -> Positive Int -> Positive Int
 subtract (Positive a) (Positive b)
   | a >= b    = Positive (a-b)
   | otherwise = Positive 0

The only other solution would be to statically guarantee that a>b,
with dependent types you could probably; but since I know next to
nothing about that, I have trouble seeing how could work with a simple
example like that: (and I would love to learn !)

1 - read two lines from stdin
2 - convert each lines to natural numbers a and b
3 - subtract b from a , a>b should be statically guaranteed
4 - print the result

David.



More information about the Beginners mailing list