[Haskell-beginners] recursion problem.
Roelof Wobben
r.wobben at home.nl
Fri Feb 6 14:05:11 UTC 2015
Roelof Wobben schreef op 6-2-2015 om 10:25:
> Hello,
>
> I have figured out how I can make from 123 [1,2,3]
>
> I did it this way :
>
> -- | convert a number to a array in pieces where a negative number
> will be a empty array.
> toDigits :: Integer -> [Integer]
> toDigits n
> | n <= 0 = []
> | otherwise = toDigits (n `div` 10) ++ [n `mod` 10]
>
>
> but now when I do toDigits 0 , I see [] as output where I was expected
> [0]
>
> But when I do toDigits 100 I see the right output [ 1,0,0] which
> surprises me because I tought that with the first 0 there will be a []
>
> Or is the n the second time [0,0] and the thirth time [0] So it will
> be like this :
>
> toDigits 100
>
> to Digits [1] ++ [ 0,0]
> toDigits [1] ++ [0] ++ [0]
>
> which leads to [1,0,0]
>
> Roelof
>
Hmm,
this is also not working :
-- | convert a number to a array in pieces where a negative number will
be a empty array.
toDigits :: Integer -> [Integer]
toDigits 0 = [0]
toDigits n
| n < 0 = []
| otherwise = toDigits (n `div` 10) ++ [n `mod` 10]
-- | convert a number to a reversed array where a negative number will
be a empty array
toDigitsRev :: Integer -> [Integer]
toDigitsRev 0 = [0]
toDigitsRev n
| n <= 0 = []
| otherwise = n `mod` 10 : toDigitsRev (n `div` 10)
-- | The main entry point.
main :: IO ()
main = do
print $ toDigits 100
print $ toDigitsRev 100
print $ toDigits 0
print $ toDigitsRev 0
print $ toDigits (-17)
print $ toDigitsRev (-17)
you get a zero too much when you use a number above 0 .
More information about the Beginners
mailing list