如何加速(或记忆)一系列相互递归的函数

时间:2012-04-13 04:37:53

标签: haskell memoization mutual-recursion

我有一个程序可以生成一系列函数fg,如下所示:

step (f,g) = (newF f g, newG f g)

newF f g x = r (f x) (g x)
newG f g x = s (f x) (g x)

foo = iterate step (f0,g0)

其中r和s是f xg x的一些无趣功能。我天真地希望将foo列为一个列表意味着当我调用第n f时,如果已经计算了它,它将不会重新计算第(n-1)个f (如果fg不是函数,就会发生这种情况)。有没有办法记住这一点而不会将整个程序拆开(例如,在所有相关参数上评估f0g0然后向上工作)?

2 个答案:

答案 0 :(得分:0)

您可能会发现Data.MemoCombinators有用(在data-memocombinators包中)。

您没有说明fg采用什么参数类型 - 如果它们都采用整数值,那么您可以像这样使用它:

import qualified Data.MemoCombinators as Memo

foo = iterate step (Memo.integral f0, Memo.integral g0)

如果需要,您也可以记住每个步骤的输出

step (f,g) = (Memo.integral (newF f g), Memo.integral (newG f g))

我希望你不要把整个程序分开。


回复你的评论:

这是我能想到的最好的。它没有经过测试,但应该按照正确的方向进行。

我担心在DoubleRational之间转换是不必要的低效率 - 如果BitsDouble个实例,我们可以使用Memo.bits代替。所以这对你来说可能最终没有任何实际用途。

import Control.Arrow ((&&&))
import Data.Ratio (numerator, denominator, (%))

memoV :: Memo.Memo a -> Memo.Memo (V a)
memoV m f = \(V x y z) -> table x y z
  where g x y z = f (V x y z)
        table = Memo.memo3 m m m g

memoRealFrac :: RealFrac a => Memo.Memo a
memoRealFrac f = Memo.wrap (fromRational . uncurry (%))
                           ((numerator &&& denominator) . toRational)
                           Memo.integral

一种不同的方法。

你有

step :: (V Double -> V Double, V Double -> V Double)
     -> (V Double -> V Double, V Double -> V Double)

如何将其更改为

step :: (V Double -> (V Double, V Double))
     -> (V Double -> (V Double, V Double))
step h x = (r fx gx, s fx gx)
  where (fx, gx) = h x

并且还要改变

foo = (fst . bar, snd . bar)
  where bar = iterate step (f0 &&& g0)

希望共享的fxgx可以带来一点加速。

答案 1 :(得分:0)

  

有没有办法记住这一点而不会将整个程序拆开(例如,在所有相关参数上评估f0和g0然后向上工作)?

这可能就是“将整个程序拆开”的意思,但这里有一个解决方案(我相信但不能测试ATM)fooX可以共享。

nthFooOnX :: Integer -> Int -> (Integer, Integer)
nthFooOnX x = 
    let fooX = iterate step' (f0 x, g0 x)
     in \n-> fooX !! n

step' (fx,gx) = (r fx gx, s fx gx)

-- testing definitions:
r = (+)
s = (*)
f0 = (+1)
g0 = (+1)

我不知道这是否保留了原始实施的精神。