Why is this Haskell expression so slow?

后端 未结 3 1412
自闭症患者
自闭症患者 2020-12-31 16:46

I\'m working on Project Euler Problem 14. Here\'s my solution.

import Data.List

collatzLength :: Int->Int
collatzLength 1 = 1
collatzLength n | odd n = 1         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 17:19

    You're assuming that the collatzLength function will be memoized. Haskell does not do automatic memoization. You'll need to do that yourself. Here's an example using the data-memocombinators package.

    import Data.List
    import Data.Ord
    import qualified Data.MemoCombinators as Memo
    
    collatzLength :: Integer -> Integer
    collatzLength = Memo.arrayRange (1,1000000) collatzLength'
      where
        collatzLength' 1 = 1
        collatzLength' n | odd n  = 1 + collatzLength (3 * n + 1)
                         | even n = 1 + collatzLength (n `quot` 2)
    
    main = print $ foldl1' max $ [(collatzLength n, n) | n <- [1..1000000]]
    

    This runs in about 1 second when compiled with -O2.

提交回复
热议问题