On Sat, Aug 22, 2009 at 12:31 PM, Derek Elkins<derek.a.elk...@gmail.com> wrote: > 2009/8/22 Eugene Kirpichov <ekirpic...@gmail.com>: >> Use 'round' instead of 'truncate'. >> >> Prelude> let numDigits = (+1) . round . logBase 10 . fromIntegral >> Prelude> map (numDigits . (10^)) [0..9] >> [1,2,3,4,5,6,7,8,9,10] >> > > round won't work because 999 is close to 1000. > > You simply need to use logBase 10 as a guess and then check the answer, e.g. > numDigits n | n < n' = e > | otherwise = e + 1 > where e = ceiling $ logBase 10 $ fromIntegral n > n' = 10^e > This will need to special case 0 which it currently doesn't do. >
Note that logBase 10 will start failing for large Integers (or rather fromIntegral will.) Writing an integer log using a binary search would be relatively easy, reasonably efficient, and would work for all Integers. _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe