
Am Sonntag 20 Dezember 2009 14:36:06 schrieb kane96@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?
Your task is to write an Enum instance for Nat. class Enum a where succ :: a -> a pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] enumFromThen :: a -> a -> [a] enumFromTo :: a -> a -> [a] enumFromThenTo :: a -> a -> a -> [a] So you have to write functions succ :: Nat -> Nat -- that's very easy pred :: Nat -> Nat -- easy too, except you have to decide whether to throw an error on pred Z or have pred Z = Z (which would fit with the required toEnum) toEnum :: Int -> Nat -- that has the additional requirement that it should return Z for negative input and so on. The first thing is to understand the Nat datatype. That models the so-called Peano numbers (or, put another way, it's built to mirror the Peano axioms for the natural numbers). Z corresponds to 0 S Z corresponds to 1, which is the successor of 0 S (S Z) corresponds to 2, which is the successor of 1 ... For non-negative n, toEnum n should be the Peano number corresponding to n and for negative n, toEnum n should be Z (to avoid exceptions). So, toEnum n | n < 0 = Z toEnum 0 = Z toEnum n = ? -- here, we know n > 0 fromEnum should be the correspondnece the other way round, so fromEnum Z = 0 fromEnum (S p) = ? -- which Int corresponds to the successor of p?