
kane96@gmx.de schrieb:
Hi, I have to write a function which maps a list of integers to a list of the corresponding nats. The following code is already there:
data Nat = Z | S Nat deriving (Eq,Ord,Show)
instance Enum Nat where toEnum i | i < 0 = error "Enum_Nat.toEnum: Negative integer" | i == 0 = Z | otherwise = S (toEnum (i-1))
this function has type "Int -> Nat" and should be wrapped into a function of type "Int -> Maybe Nat" that does not produce a runtime error if called with negative input.
the function should be: mapIntsToNats :: [Int] -> Maybe [Nat] so for example: [2,0,1,3] should make: [S (S Z), Z, S Z, S (S (S Z))]
how can I do that?
Have you heard about monads and mapM? (The type constructor Maybe is an instance of the class Monad.) Cheers Christian