This pertains to Emily's answer here: https://stackoverflow.com/a/13850560/2026752
ansMap :: M.Map Integer Int
ansMap = M.fromAscList [(i, collatz i) | i <- [1..1000000]]
where collatz 1 = 0
collatz x = if x' <= 1000000 then 1 + ansMap M.! x'
else 1 + collatz x'
where x' = if even x then x `div` 2 else x*3 + 1
-- this code is really fast
fst $ maximumBy (comparing snd) $ M.toList ansMap
This seemed like a reasonable strategy, so I decided to take 1000000 and feed it as a variable to the function, so I could compute the Collatz sequence for even more numbers:
ansMap :: Integer -> M.Map Integer Int
ansMap n = M.fromAscList [(i, collatz i) | i <- [1..n]]
where collatz 1 = 0
collatz x = if x' <= n then 1 + ansMap n M.! x'
else 1 + collatz x'
where x' = if even x then x `div` 2 else x*3 + 1
-- but then suddenly this is slow
fst $ maximumBy (comparing snd) $ M.toList ansMap 1000000
This confuses me, since all I did was take n out and pass it back in! I don't know much about the Haskell runtime. Please help me understand! Thank you in advance.