Search code examples
haskelltailrecursion-modulo-cons

Will this Haskell code take too much memory?


As in this code:

import Data.Char
groupsOf _ [] = []
groupsOf n xs = 
    take n xs : groupsOf n ( tail xs )

problem_8 x = maximum . map product . groupsOf 5 $ x
main = do t <- readFile "p8.log" 
      let digits = map digitToInt $concat $ lines t
      print $ problem_8 digits

I realize that in Haskell many programs construct and seem to store some intermediate results, such as the groupsOf list in the above code. The above code is the reference answer for Euler project problem 8, taken from Haskell website. The original question ask for the largest product of 5 consecutive digits in a very long chain of digits such as 45343231635723421312443535767983456. So the code will calculate all the products and store it as a list. In other languages I think they will only keep a temporary largest value and discard anything smaller.

So does groupsOf really stores all the intermediate results? what if the problem scales up? Will it allocate too much memory?


Solution

  • No, not because of groupsOf. That one will only need to keep one group in memory at a time. However, maximum might build up a large thunk since it's too lazy, so make sure to either compile with -O or -O2 so that strictness analysis is performed, or use foldl1' max instead1.

    1 foldl1' is found in Data.List