This is the Question 14.
import Data.Array
import Data.List
import Data.Ord (comparing)
syrs n = a
where
-- For those who don't want to lookup array in the reference
-- the following line creates an array indexed from 1 to n
-- using the list provided. And a ! x is the syntax for a[x] in some other languages.
a = listArray (1,n) $ 0 : [1 + syr n x | x <- [2..n]] -------- 2
syr n x = if x' <= n -------- 1
then a ! x' -------- 1
else 1 + syr n x'
where
x' = if even x
then x `div` 2
else 3 * x + 1
main = print $ maximumBy (comparing snd) $ assocs $ syrs 1000000
Above is the suggested solution for Project Euler Q14 on wiki.haskell.org. The algorithm is largely the same to mine (but mine runs forever while this runs in 2sec).
Question:
In line 2, it calls syr n x
. Suppose x = 3
, x' = 10
, 10 < n
, it will proceed with then
clause : a ! 10
. But at this time, a ! 10
is not yet calculated. How does the program proceed then?