[Haskell-beginners] Enum for natural numbers

Deniz Dogan deniz.a.m.dogan at gmail.com
Sun Dec 20 08:45:02 EST 2009

2009/12/20  <kane96 at gmx.de>:
> Maybe I didn't understand the exercise if have to do. It says:
> "Write the instance Enum Nat where toEnum is defined as a total function that returns Z for negative integers. Some examples:
> *Main> toEnum (-1) :: Nat
> Z
> *Main> toEnum 0 :: Nat
> Z
> *Main> toEnum 1 :: Nat
> S Z
> *Main> fromEnum (S (S Z))
> 2
> so I did:
> data Nat = Z | S Nat deriving (Eq,Ord,Show)
> instance Enum Nat where
> toEnum x|x > 0 = S Z
>        |otherwise = Z
> somehow it looks really wrong. Do you understand want I have to do and how it should look like?

In your current definition of toEnum, you always return "S Z" (in
other words, "1", "the successor of zero") for any integer i > 0. This
is clearly incorrect as you said. Your "otherwise" guard is correct,
but the other one is not. I get the feeling that this exercise is
about learning how to use recursion, so look into that.

A few relevant links:
http://en.wikibooks.org/wiki/Haskell/Recursion (the factorial example)

Hope that helps

Deniz Dogan

More information about the Beginners mailing list