I'm trying to solve #15 from Project Euler, this is my first solution import Data.List
type Location = (Int,Int)
boardX = 20
boardY = 20
stepBack :: Location -> [Location]
stepBack (x,y) = [(x-1,y), (x,y-1)]
legalStep :: Location -> Bool
legalStep (x,y) = x >= 0 && y >= 0
iteractStep :: Int -> [[Location]]
iteractStep 0 = [[(boardX, boardY)]]
iteractStep n = [x:y|y <- iteractStep (n-1), x<- stepBack (head y), legalStep x]
main :: IO ()
main = putStrLn $ show $ length $ iteractStep (boardX + boardY)
this is very slow, i find there are so many sub-problem re-computed, i try to memorize sub-problem answer, then i found this example:
memoized_fib :: Int -> Integer
memoized_fib = (map fib [0 ..] !!)
where fib 0 = 0
fib 1 = 1
fib n = memoized_fib (n-2) + memoized_fib (n-1)
i try it in ghci, i found it actually memorize sub-problem result, i can't understand how this code can memorize result, it looks like
map fib [0 ..]
is global, but i think it is method scope (only exists at every method call), why it can memorize result?