[clean-list] stupid question

jgogolin at tampabay.rr.com jgogolin at tampabay.rr.com
Tue Dec 11 17:23:32 MET 2007


---- David Minor <david-m at orbotech.com> wrote: 
> I must be missing something obvious, I'm going through the tutorial, why
> doesn't the following terminate on a one digit number when given 999 as
> expected?
>  
> module test
> import StdEnv
>  
> Start = [isum 18, isum 3, isum 999]
>  
> isum :: Int -> Int
> isum x
>             | x<10 = x
>             | otherwise = ones x + isum (x / 10)
>  
> div9 :: Int -> Bool
> div9 x
>             | isum x == 9 = True
>             | otherwise = False
>             
> ones :: Int -> Int
> ones x = (x - ((x / 10) * 10))
>  
> Thanks,
> David
>  


I think what you're looking for is closer to:
Start = [div9 18, div9 3, div9 999]
 
isum :: Int -> Int
isum x
            | x<10 = x
            | otherwise = ones x + isum (x / 10)
 
div9 :: Int -> Bool
div9 x
            | isum x > 9 div9 isum x
            | isum x == 9 = True
            | otherwise = False
            
ones :: Int -> Int
ones x = (x - ((x / 10) * 10))


The trick here is to get div9 to recurse on isum until a single digit is the result.  As stated by others, isum is doing exactly as it's supposed to.

Johnn


More information about the clean-list mailing list