[Haskell-cafe] Re: Positive integers

Henning Thielemann lemming at henning-thielemann.de
Fri Mar 24 07:55:55 EST 2006

On Fri, 24 Mar 2006, Aaron Denney wrote:

> On 2006-03-24, Daniel McAllansmith <dagda at xtra.co.nz> wrote:
>> Unless I've missed it, there is no typeclass for positive integers in GHC.
>> Is there any particular reason it doesn't exist?
> The number of useable operations is small, and checks for leaving the
> domain would have to be done all the time.  It basically doesn't buy
> anything.

A new type, say Cardinal as in Modula, would document for the user of a 
function that only non-negative numbers are allowed and the function 
writer can be sure, that only non-negative numbers are passed. Today 
function writers have to check explicitly for negative numbers, when they 
are not wanted. With a Cardinal type some of these checks can be dropped 
because of the static guarantee that Cardinals are never negative.
  Further on think of QuickCheck: A Cardinal type with an Arbitrary 
instance would save us the (>=0) condition and it would reduce the number 
of tests that must be skipped because of non-fulfilled conditions. Because 
I was confronted with adding positivity checks to QuickCheck properties 
quite frequently, I finally wrote wrappers
  newtype Cardinal = Cardinal Integer deriving (Show, Read, Eq, Ord, Ix)
  newtype Card     = Card     Int     deriving (Show, Read, Eq, Ord, Ix)
   in order to simplify such checks.

Since the pros and cons of new types are true for every number type, the 
discussion whether Cardinal should be supported or not ends up with the 
question how often it can be used. When I look through my Modula programs 
I encounter CARDINAL quite often, so yes, it seems to be useful. Inductive 
definitions of functions of integers need a base case - which is often 
zero. That is such functions are intended for Cardinals rather than 
Integers. The (n+k) pattern are often defended because of its use in 
inductive definitions. So I claim that Cardinals are at least as important 
as (n+k) patterns. :-)

More information about the Haskell-Cafe mailing list