[Haskell-beginners] Re: list of integers to list of nats
Christian Maeder
Christian.Maeder at dfki.de
Sat Feb 20 09:59:52 EST 2010
kane96 at 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.
More information about the Beginners
mailing list