Memoization of multi-parameter function in Haskell
The following example of a function using memoization is presented on this
page:
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)
What if we wanted to memoize a multi-parameter function, though? We could
create a 'multiplied Fibonacci', for example, that would be defined f(m,n)
= m*f(m,n-2) + m*f(m,n-1). I modified the code above for this 'multiplied
Fibonacci' function as follows:
mult_fib :: Integer -> Int -> Integer
mult_fib mult = (map (m_fib mult) [0..] !!)
where m_fib _ 0 = 0
m_fib _ 1 = 1
m_fib m n = m*(mult_fib m (n-2)) + m*(mult_fib m (n-1))
The runtime of the modified function is exponential, even though the
original is linear. Why does this technique not work in the second case?
Also, how could the function be modified to make use of memoization
(without using library functions)?
No comments:
Post a Comment