[Haskell-beginners] Finding Keith Numbers with Haskell

Jack Mott jack.mott at gmail.com
Tue Nov 11 00:32:14 UTC 2014


I'm on day 2 of learning Haskell, and decided to write a program to find
Keith Numbers as my first project. So far so good, I have some code that
does the job (see below).  First I would just like to ask others to look it
over and let me know if I am doing anything particularly wrong or not
advised here.

Also, I am using the "isKeithHelper" function because I didn't know how to
make use of the filter function directly with isKeith, because isKeith
takes two parameters.  I'm pretty sure there is a better way to handle
that, any tips?

Lastly, I'd like to make this as efficient as possible. At the moment I am
adding [s] to the end of the list in the isKeith function, which I know is
O(n) instead of O(1). I don't think there is a way to avoid either that or
having to use drop which would have the same downside.  Is this a case
where a Sequence or Vector might be more useful? How would I convert this
to use a Sequence instead?



import Data.Time.Clock.POSIX
import Data.Digits

isKeith :: Integer -> [Integer] ->  Bool
isKeith n l
    | s == n            = True
    | s > n             = False
    | otherwise         = isKeith n x (l ++ [s])
    where
        s = sum l

isKeithHelper :: Integer -> Bool
isKeithHelper n = isKeith  n  (digits 10 n)


main :: IO ()
main = do
        start <- getPOSIXTime
        print (filter isKeithHelper [1000..9999])
        end <- getPOSIXTime
        print (end - start)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20141110/1d202443/attachment.html>


More information about the Beginners mailing list