Memoization with recursion

前端 未结 3 491
醉梦人生
醉梦人生 2021-01-12 06:18

I am trying to understand Haskell realization of memoization , but I don\'t get how it works:

memoized_fib :: Int -> Integer
memoized_fib = (map fib [0..]         


        
3条回答
  •  梦毁少年i
    2021-01-12 07:10

    Maybe it's clearer written it as:

    memoized_fib n = (map fib [0..]) !! n
    

    so it's just taking the nth element from the list, and the list is evaluated lazily.

    This operator section stuff is exactly the same as normal partial application, but for infix operators. In fact, if we write the same form with a regular function instead of the !! infix operator, see how it looks:

    import Data.List (genericIndex)
    
    memoized_fib :: Int -> Integer
    memoized_fib = genericIndex (map fib [0..])
        where fib 0 = 0
                  fib 1 = 1
                  fib n = memoized_fib(n - 2) + memoized_fib(n - 1)
    

提交回复
热议问题