[Haskell-cafe] question on types

Ketil Malde ketil at malde.org
Wed Feb 18 04:57:47 EST 2009


Luke Palmer <lrpalmer at gmail.com> writes:

> 2009/2/17 Daryoush Mehrtash <dmehrtash at gmail.com>

>> Is there a way to define a type with qualification on top of existing type
>> (e.g.  prime numbers)?   Say for example I want to define a computation that
>> takes a prime number and generates a string.   Is there any way I can do
>> that in Haskell?

> You can by providing an abstraction barrier:

Or you can define:

   newtype Prime = Prime Int -- 'Prime i' represents the i'th prime

This has the advantage that it is physically impossible to put a
non-prime value into the Prime data type.  The disadvantage is that
if you somehow need the numerical value of the i'th prime, you need to
calculate it:

   primes :: [Integer]
   primes = 2 : sieve ...

   instance show Prime where 
        show Prime i = show (primes!!i)

-k
-- 
If I haven't seen further, it is by standing in the footprints of giants


More information about the Haskell-Cafe mailing list