[Haskell-cafe] Natural Numbers: Best implementation?
mark.spezzano at chariot.net.au
Thu Mar 12 22:54:39 EDT 2009
I was wondering what the best way to implement Natural number would be. Is
there a package which already does this?
Here are some options:
1. Dont bother. Just use Integer.
2. Use the type
data Natural = Zero | Succ !Natural
3. Use the following definition taken from the Gentle Introduction to
newtype Natural = MakeNatural Integer
toNatural ::Integer-> Integer
toNatural x | x < 0 = error Cant create negative naturals!
| otherwise = MakeNatural x
fromNatural :: Natural -> Integer
fromNatural (MakeNatural i) = i
instance Num Natural where
fromInteger = toNAtural
x + y = toNatural (fromNatural x + fromNatural y)
x y = etc..
x * y = etc...
Which method is best? So far, Ive been picking option #1 just leaving
things as they are and using Integer to keep things simple.
Ive got that feeling that  would be fast and  would be slow. Comment
appreciated on the merits of each.
No virus found in this outgoing message.
Checked by AVG.
Version: 7.5.557 / Virus Database: 270.11.12/1998 - Release Date: 12/03/2009
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe