[Haskell-begin] Maximum of a List?

Steve Klabnik steve.klabnik at gmail.com
Sat Jul 26 17:54:57 EDT 2008


Hello everyone-

I'm working on some project Euler problems today, and I'm stuck on one. It's
not the problem itself that's the problem, it's that finding the maximum of
a list makes me run out of heap space!

http://projecteuler.net/index.php?section=problems&id=14

my code:

import Data.List

f :: Int -> Int -> Int
f acc x
    | x == 1 = acc
        | even x = f (acc + 1) (x `div` 2)
        | otherwise = f (acc + 1) (3 * x + 1)

answer = (foldl' max 0) $ map (f 1) [1 .. 999999]

I tried using 'foldl' max ' instead of 'maximum' because I thought that
foldl' was supposed to work better than foldl or something...I could be
confused on that point. Anyway, here's what I get...

  / _ \ /\  /\/ __(_)
 / /_\// /_/ / /  | |      GHC Interactive, version 6.4, for Haskell 98.
/ /_\\/ __  / /___| |      http://www.haskell.org/ghc/
\____/\/ /_/\____/|_|      Type :? for help.

Loading package base-1.0 ... linking ... done.
Prelude> :l ..\test.hs
Compiling Main             ( ..\test.hs, interpreted )
Ok, modules loaded: Main.
*Main> answer
GHC's heap exhausted: current limit is 268435456 bytes;
Use the `-M<size>' option to increase the total heap size.

I also tried writing a simple 'max' function that I thought was tail
recursive, and that that would help. Same error. I'm finding it hard to
believe that finding a maximum of a list of a million small integers would
cause this kind of overflow...is it really that big of a problem?

Any help would be appreciated. I have a feeling I'll run into this problem
again in the future.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20080726/b7645d1a/attachment.htm


More information about the Beginners mailing list