[Haskell-beginners] recursion problem.

YCH dontdieych at gmail.com
Fri Feb 6 10:06:56 UTC 2015


On Fri, Feb 6, 2015 at 6:25 PM, Roelof Wobben <r.wobben at home.nl> wrote:
> 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]

toDigits 100
toDigits 10 ++ [0]
toDigits 1 ++ [0] ++ [0]
[1] ++ [0] ++ [0]
[1,0,0]

toDigits 0
[] -- because first guard clause

0 is valid input. It should be dealt different from negative number.

-- 
YCH






More information about the Beginners mailing list