
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)) 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? -- NEU: Mit GMX DSL über 1000,- ¿ sparen! http://portal.gmx.net/de/go/dsl02

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))
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))]
Since the result type is "Maybe [Nat]" the result should be: Just [S (S Z), Z, S Z, S (S (S Z))] I suppose the result should be Nothing if the input list contains any negative integer.
how can I do that?
Who is your instructor? The most basic approach is do pattern-match on the input list. mapIntsToNats l = case l of [] -> ... h : t -> ... and call "mapIntsToNats" recursively on the tail "t". The recursive result is (also) of type "Maybe [Nat]", therefore you have to further pattern-match this result and insert the converted head element "h". Is this enough to help you? C.

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
participants (2)
-
Christian Maeder
-
kane96@gmx.de