[Haskell-beginners] Enum for natural numbers

Daniel Fischer daniel.is.fischer at web.de
Sun Dec 20 15:55:49 EST 2009


Am Sonntag 20 Dezember 2009 21:35:45 schrieb kane96 at gmx.de:
> > As a further example,
> >
> > replicate :: Int -> a -> [a]
> > replicate n x
> >
> >     | n <= 0    = []
> >     | otherwise = x:replicate (n-1) x
> >
> > may help.
>
> my problem is that I don't know how to use Enum correctly and didn't find
> any helpfull example
>

toEnum and fromEnum should give the correspondence

0 <-> Z
1 <-> S Z
2 <-> S (S Z)
3 <-> S (S (S Z))
4 <-> S (S (S (S Z)))
5 <-> S (S (S (S (S Z))))

and so on. Of course, defining toEnum entirely via pattern matching

toEnum 0 = Z
toEnum 1 = S Z
toEnum 2 = S (S Z)
toEnum 3 = S (S (S Z))
...

will take too long to type (and will drive the compiler mad), so define it via recursion. 
It will strongly resemble the definition of replicate above.

The definition of fromEnum will resemble that of genericLength, 
http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/src/Data-
List.html#genericLength


More information about the Beginners mailing list