[Haskell-beginners] Finding Keith Numbers with Haskell

Rein Henrichs rein.henrichs at gmail.com
Tue Nov 11 02:50:23 UTC 2014

Since summing is commutative (sum [a,b] = sum [b,a]), it doesn't matter
what order they appear in. You can start out by reversing the digits and
then by taking from and adding to the beginning of the list instead of the
end. Also, isKeith needs to know the length of the decimal representation
of n. Since you are already computing that representation in isKeithHelper,
it might be best to compute this there as well and pass it into isKeith.

(Also please consider the criterion library for benchmarking.)

> import Data.Digits

> isKeith :: Int -> Bool
> isKeith n = let ds = digitsRev 10 n in isKeith' n (length ds) ds

> isKeith' :: Int -> Int -> [Int] ->  Bool
> isKeith' n len ds
>   | n == s = True
>   | s > n = False
>   | otherwise = isKeith' n len (take len (s : ds))
>   where s = sum ds

> main :: IO ()
> main = print (isKeith 197)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20141110/3afec4a3/attachment.html>

More information about the Beginners mailing list