[Haskell-cafe] how to optmize this code?

Christian Maeder Christian.Maeder at dfki.de
Thu Mar 31 11:45:00 CEST 2011


Am 31.03.2011 05:59, schrieb Felipe Almeida Lessa:
> On Wed, Mar 30, 2011 at 2:39 PM, Gilberto Garcia<giba.dmb at gmail.com>  wrote:
>> fkSum :: Int ->  [Int] ->  Int
>> fkSum a [] = 0
>> fkSum a (b) = foldl (+) 0 (filter (\x ->  isMultiple x b) [1..a])
>
> Daniel Fischer and Yves Parès gave you good suggestions about
> implementing a different, better algorithm for you problem.  However,
> there's one small thing about your current code.  Instead of foldl,
> you should use foldl' (use "import Data.List"), which is strict in the
> accumulator.  Most of the time you want foldl' instead of foldl.  You
> can learn more about the list folds here [1].

Since we don't have a function sum' in the Prelude (should we have it?) 
I wonder what happens if you just use "sum". Will the "sum" (based on 
sum' so without -DUSE_REPORT_PRELUDE) be strict enough?

#ifdef USE_REPORT_PRELUDE
sum                     =  foldl (+) 0
product                 =  foldl (*) 1
#else
sum     l       = sum' l 0
   where
     sum' []     a = a
     sum' (x:xs) a = sum' xs (a+x)
product l       = prod l 1
   where
     prod []     a = a
     prod (x:xs) a = prod xs (a*x)
#endif

Cheers C.

P.S.

isMultiple a = any ((== 0) . mod a)

>
> HTH,
>
> [1] http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl%27




More information about the Haskell-Cafe mailing list