memoization

When is memoization automatic in GHC Haskell?

蹲街弑〆低调 提交于 2019-11-26 02:05:59
问题 I can\'t figure out why m1 is apparently memoized while m2 is not in the following: m1 = ((filter odd [1..]) !!) m2 n = ((filter odd [1..]) !! n) m1 10000000 takes about 1.5 seconds on the first call, and a fraction of that on subsequent calls (presumably it caches the list), whereas m2 10000000 always takes the same amount of time (rebuilding the list with each call). Any idea what\'s going on? Are there any rules of thumb as to if and when GHC will memoize a function? Thanks. 回答1: GHC does

How is this fibonacci-function memoized?

寵の児 提交于 2019-11-26 01:56:49
问题 By what mechanism is this fibonacci-function memoized? fib = (map fib\' [0..] !!) where fib\' 1 = 1 fib\' 2 = 1 fib\' n = fib (n-2) + fib (n-1) And on a related note, why is this version not? fib n = (map fib\' [0..] !! n) where fib\' 1 = 1 fib\' 2 = 1 fib\' n = fib (n-2) + fib (n-1) 回答1: The evaluation mechanism in Haskell is by-need : when a value is needed, it is calculated, and kept ready in case it is asked for again. If we define some list, xs=[0..] and later ask for its 100th element,

How to determine the longest increasing subsequence using dynamic programming?

落爺英雄遲暮 提交于 2019-11-26 00:13:31
问题 I have a set of integers. I want to find the longest increasing subsequence of that set using dynamic programming. 回答1: OK, I will describe first the simplest solution which is O(N^2), where N is the size of the collection. There also exists a O(N log N) solution, which I will describe also. Look here for it at the section Efficient algorithms. I will assume the indices of the array are from 0 to N - 1. So let's define DP[i] to be the length of the LIS (Longest increasing subsequence) which

What is memoization and how can I use it in Python?

喜欢而已 提交于 2019-11-25 22:57:09
问题 I just started Python and I\'ve got no idea what memoization is and how to use it. Also, may I have a simplified example? 回答1: Memoization effectively refers to remembering ("memoization" → "memorandum" → to be remembered) results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. You can think of it as a cache for method results. For further details, see page 387 for the definition in Introduction To Algorithms (3e),