Haskell: memoization

后端 未结 1 1979
无人及你
无人及你 2021-01-24 18:02

I\'m trying to relearn Haskell, after many years away and forgetting everything, and I find myself still confused my memoization. In particular, I\'m trying to write a

相关标签:
1条回答
  • 2021-01-24 19:00

    With

    nders :: Int -> Integer
    nders n = (map der [0 ..]) !! n
      where der 0 = 1
            der 1 = 0
            der n = (nders (n-2) + nders (n-1)) * toInteger (n-1)
    

    the map der [0..] part will be recomputed for any application of nders, especially including the recursive calls in der.

    You can move out the definition of the tabulation so that it doesn't (syntactically) depend on n, which should do the right thing:

    nders :: Int -> Integer
    nders = (memoized !!)
      where 
        memoized = map der [0 ..]
    
        der 0 = 1
        der 1 = 0
        der n = (nders (n-2) + nders (n-1)) * toInteger (n-1)
    
    0 讨论(0)
提交回复
热议问题