[Haskell-cafe] recursion problem part 2
Jeffrey Brown
jeffbrown.the at gmail.com
Fri Feb 6 20:41:13 UTC 2015
Here's a solution:
lastDigit x = mod x 10
remainingDigits x = (x - lastDigit x) `div` 10
listDigits x
| x < 10 = [x]
| otherwise = (listDigits $ remainingDigits x) ++ [lastDigit x]
Here's a faster one:
listDigits2 x
| x < 10 = [x]
| otherwise = (listDigits $ remainingDigits) ++ [lastDigit]
where lastDigit = mod x 10
remainingDigits = (x - lastDigit) `div` 10
On Fri, Feb 6, 2015 at 8:07 AM, Roelof Wobben <r.wobben at home.nl> wrote:
> Jerzy Karczmarczuk schreef op 6-2-2015 om 16:57:
>
>>
>> Le 06/02/2015 16:48, Roelof Wobben a écrit :
>>
>>> Im only sure that somehow I take the wrong turn somewhere because I
>>> cannot figure out why I do not get the right answer.
>>>
>>> I think I have the value of n wrong.
>>>
>> Did you read my answer entirely? Do so, find the red fat line
>>
>> You take n=1, and you write: n<10 not True.
>> You don't need to be a specialist on recursion, to see the error.
>>
>> Jerzy
>>
>>
> oke,
>
> Another try :
>
> toDigits :: Integer -> [Integer]
> toDigits n
> | n < 0 = []
> | n < 10 = [n]
> | otherwise = toDigits (n `div` 10) ++ [n `mod` 10]
>
> isDigits 1
>
> n < 0 not true.
> n < 10 true so [1]
>
> IsDigits 12
>
> n < 0 not true
> n < 10 not true
> toDigits 1 + [2]
>
> toDigits 1 + [2]
>
> n < 0 not true
> n < 10 true [1] ++ [2]
>
> 1 ++2 = [1,2]
>
> I think I understand it finnaly.
>
>
> Roelof
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20150206/f4de9921/attachment.html>
More information about the Haskell-Cafe
mailing list