Haskell 中的记忆化?
关于如何在 Haskell 中有效求解以下函数的任何指针,对于大数 (n > 108)
f(n) = max(n, f(n/2) + f(n/3) + f(n/4))
我已经看过 Haskell 中记忆化求解斐波那契数列的示例 数字,涉及(惰性地)计算所有斐波那契数 直到所需的n。但在这种情况下,对于给定的 n,我们只需要 计算很少的中间结果。
谢谢
Any pointers on how to solve efficiently the following function in Haskell, for large numbers (n > 108)
f(n) = max(n, f(n/2) + f(n/3) + f(n/4))
I've seen examples of memoization in Haskell to solve fibonacci
numbers, which involved computing (lazily) all the fibonacci numbers
up to the required n. But in this case, for a given n, we only need to
compute very few intermediate results.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我们可以通过创建一个可以在亚线性时间内索引的结构来非常有效地做到这一点。
但首先,
让我们定义
f
,但让它使用“开放递归”而不是直接调用自身。您可以使用
fix f
获得未记忆的f
这将让您测试
f
是否符合您对f 小值的意思。
通过调用,例如:fix f 123 = 144
我们可以通过定义来记住这一点:
表现还算不错,并取代了将要花费的时间 O(n^3) 花一些时间来记住中间结果。
但仅通过索引来查找
mf
的记忆答案仍然需要线性时间。这意味着像这样的结果是可以容忍的,但结果并没有比这更好。我们可以做得更好!
首先,让我们定义一个无限树:
然后我们将定义一种对其进行索引的方法,这样我们就可以在 O(log n) 中找到索引为
n
的节点时间:...我们可能会发现一棵充满自然数的树很方便,因此我们不必摆弄这些索引:
因为我们可以索引,所以您可以将树转换为列表:
您可以检查到目前为止,通过验证
toList nats
为您提供[0..]
现在,
工作方式与上面的列表类似,但不是花费线性时间来查找每个节点,可以在对数时间内追到它。
结果要快得多:
事实上,它的速度要快得多,您可以遍历上面的
Int
并将其替换为Integer
,几乎可以立即获得大得离谱的答案。 - 实现基于树的记忆化的盒子库,使用 MemoTrie:
We can do this very efficiently by making a structure that we can index in sub-linear time.
But first,
Let's define
f
, but make it use 'open recursion' rather than call itself directly.You can get an unmemoized
f
by usingfix f
This will let you test that
f
does what you mean for small values off
by calling, for example:fix f 123 = 144
We could memoize this by defining:
That performs passably well, and replaces what was going to take O(n^3) time with something that memoizes the intermediate results.
But it still takes linear time just to index to find the memoized answer for
mf
. This means that results like:are tolerable, but the result doesn't scale much better than that. We can do better!
First, let's define an infinite tree:
And then we'll define a way to index into it, so we can find a node with index
n
in O(log n) time instead:... and we may find a tree full of natural numbers to be convenient so we don't have to fiddle around with those indices:
Since we can index, you can just convert a tree into a list:
You can check the work so far by verifying that
toList nats
gives you[0..]
Now,
works just like with list above, but instead of taking linear time to find each node, can chase it down in logarithmic time.
The result is considerably faster:
In fact it is so much faster that you can go through and replace
Int
withInteger
above and get ridiculously large answers almost instantaneouslyFor an out-of-the-box library that implements the tree based memoization, use MemoTrie:
Edward 的答案是如此精彩,我复制了它并提供了
memoList
和memoTree
组合器,以开放递归形式记忆函数。Edward's answer is such a wonderful gem that I've duplicated it and provided implementations of
memoList
andmemoTree
combinators that memoize a function in open-recursive form.这不是最有效的方法,但确实会记住:
当请求
f !! 144
,经检查f!! 143
存在,但未计算其确切值。它仍然被设置为某种未知的计算结果。计算出的唯一精确值是所需的值。所以最初,对于计算了多少,程序一无所知。
当我们发出请求时
f !! 12
,它开始做一些模式匹配:现在它开始计算
这递归地对 f 提出了另一个要求,所以我们计算
现在我们可以滴流备份一些
这意味着程序现在知道:
继续滴流向上:
这意味着程序现在知道:
现在我们继续计算
f!!6
:意味着程序现在知道:
现在我们继续计算
f!!12
:这 意味着程序现在知道:
所以计算是相当懒惰地完成的。程序知道
f 的某个值!! 8
存在,它等于g 8
,但它不知道g 8
是什么。Not the most efficient way, but does memoize:
when requesting
f !! 144
, it is checked thatf !! 143
exists, but its exact value is not calculated. It's still set as some unknown result of a calculation. The only exact values calculated are the ones needed.So initially, as far as how much has been calculated, the program knows nothing.
When we make the request
f !! 12
, it starts doing some pattern matching:Now it starts calculating
This recursively makes another demand on f, so we calculate
Now we can trickle back up some
Which means the program now knows:
Continuing to trickle up:
Which means the program now knows:
Now we continue with our calculation of
f!!6
:Which means the program now knows:
Now we continue with our calculation of
f!!12
:Which means the program now knows:
So the calculation is done fairly lazily. The program knows that some value for
f !! 8
exists, that it's equal tog 8
, but it has no idea whatg 8
is.这是爱德华·克梅特(Edward Kmett)出色答案的附录。
当我尝试他的代码时,
nats
和index
的定义似乎相当神秘,因此我编写了一个更容易理解的替代版本。我根据
index'
和nats'
定义了index
和nats
。index' t n
是在[1..]
范围内定义的。 (回想一下,index t
是在[0..]
范围内定义的。)它通过将n
视为字符串来搜索树位,并反向读取这些位。如果该位为1
,则采用右侧分支。如果该位为0
,则采用左侧分支。当到达最后一位(必须是1
)时它会停止。正如为
index
定义nats
一样,index nats n == n
始终为 true,nats'
为为index'
定义。现在,
nats
和index
只是nats'
和index'
,但值移动了 1:This is an addendum to Edward Kmett's excellent answer.
When I tried his code, the definitions of
nats
andindex
seemed pretty mysterious, so I write an alternative version that I found easier to understand.I define
index
andnats
in terms ofindex'
andnats'
.index' t n
is defined over the range[1..]
. (Recall thatindex t
is defined over the range[0..]
.) It works searches the tree by treatingn
as a string of bits, and reading through the bits in reverse. If the bit is1
, it takes the right-hand branch. If the bit is0
, it takes the left-hand branch. It stops when it reaches the last bit (which must be a1
).Just as
nats
is defined forindex
so thatindex nats n == n
is always true,nats'
is defined forindex'
.Now,
nats
andindex
are simplynats'
andindex'
but with the values shifted by 1:正如 Edward Kmett 的回答所述,为了加快速度,您需要缓存昂贵的计算并能够快速访问它们。
为了保持函数非单子,构建无限惰性树的解决方案,并使用适当的方法对其进行索引(如之前的帖子所示)可以实现该目标。如果您放弃函数的非单子性质,则可以将 Haskell 中可用的标准关联容器与“类状态”单子(例如 State 或 ST)结合使用。
虽然主要缺点是您获得了非单子函数,但您不必再自己对结构进行索引,而只需使用关联容器的标准实现即可。
为此,您首先需要重写函数以接受任何类型的 monad:
对于您的测试,您仍然可以使用 Data.Function.fix 定义一个不进行记忆的函数,尽管它有点冗长
:然后可以将 State monad 与 Data.Map 结合使用来加快速度:
通过微小的更改,您可以调整代码以与 Data.HashMap 配合使用:
除了持久数据结构,您还可以尝试可变数据结构(例如 Data .HashTable)与 ST monad 结合:与
没有任何记忆的实现相比,这些实现中的任何一个都允许您在大量输入的情况下在微秒内获得结果,而不必等待几秒钟。
使用 Criterion 作为基准,我可以观察到 Data.HashMap 的实现实际上比 Data.Map 和 Data.HashTable 的执行稍好(大约 20%),两者的时间非常相似。
我发现基准测试的结果有点令人惊讶。我最初的感觉是 HashTable 会优于 HashMap 实现,因为它是可变的。最后的实现中可能隐藏着一些性能缺陷。
As stated in Edward Kmett's answer, to speed things up, you need to cache costly computations and be able to access them quickly.
To keep the function non monadic, the solution of building an infinite lazy tree, with an appropriate way to index it (as shown in previous posts) fulfills that goal. If you give up the non-monadic nature of the function, you can use the standard associative containers available in Haskell in combination with “state-like” monads (like State or ST).
While the main drawback is that you get a non-monadic function, you do not have to index the structure yourself anymore, and can just use standard implementations of associative containers.
To do so, you first need to re-write you function to accept any kind of monad:
For your tests, you can still define a function that does no memoization using Data.Function.fix, although it is a bit more verbose:
You can then use State monad in combination with Data.Map to speed things up:
With minor changes, you can adapt the code to works with Data.HashMap instead:
Instead of persistent data structures, you may also try mutable data structures (like the Data.HashTable) in combination with the ST monad:
Compared to the implementation without any memoization, any of these implementation allows you, for huge inputs, to get results in micro-seconds instead of having to wait several seconds.
Using Criterion as benchmark, I could observe that the implementation with the Data.HashMap actually performed slightly better (around 20%) than that the Data.Map and Data.HashTable for which the timings were very similar.
I found the results of the benchmark a bit surprising. My initial feeling was that the HashTable would outperform the HashMap implementation because it is mutable. There might be some performance defect hidden in this last implementation.
几年后,我看到了这个,并意识到有一种简单的方法可以使用 zipWith 和辅助函数在线性时间内记住它:
dilate 具有方便的属性, > 扩大 n xs !!我==xs!! div i n。
因此,假设我们给出 f(0),这将简化计算,
看起来很像我们原来的问题描述,并给出一个线性解决方案(
sum $ take n fs
将花费 O(n) )。A couple years later, I looked at this and realized there's a simple way to memoize this in linear time using
zipWith
and a helper function:dilate
has the handy property thatdilate n xs !! i == xs !! div i n
.So, supposing we're given f(0), this simplifies the computation to
Looking a lot like our original problem description, and giving a linear solution (
sum $ take n fs
will take O(n)).Edward Kmett 答案的另一个附录:一个独立的示例:
按如下方式使用它来记忆具有单个整数参数的函数(例如斐波那契):
仅缓存非负参数的值。
要缓存负参数的值,请使用
memoInt
,定义如下:要缓存具有两个整数参数的函数的值,请使用
memoIntInt
,定义如下:Yet another addendum to Edward Kmett's answer: a self-contained example:
Use it as follows to memoize a function with a single integer arg (e.g. fibonacci):
Only values for non-negative arguments will be cached.
To also cache values for negative arguments, use
memoInt
, defined as follows:To cache values for functions with two integer arguments use
memoIntInt
, defined as follows:没有索引的解决方案,并且不基于 Edward KMETT 的解决方案。
我将公共子树分解为公共父树(
f(n/4)
在f(n/2)
和f(n/4)< 之间共享/code>,并且
f(n/6)
在f(2)
和f(3)
之间共享。通过将它们保存为父级中的单个变量,子树的计算只需完成一次。该代码不容易扩展到一般的记忆功能(至少,我不知道如何做到这一点),并且您确实必须考虑子问题如何重叠,但策略应该起作用对于一般的多个非整数参数。 (我想到了两个字符串参数。)
每次计算后都会丢弃备忘录。 (再次,我在考虑两个字符串参数。)
我不知道这是否比其他答案更有效。从技术上讲,每次查找只需一两个步骤(“查看您的孩子或您孩子的孩子”),但可能会使用大量额外的内存。
编辑:此解决方案尚不正确。共享不完整。编辑:现在应该正确共享子子项,但我意识到这个问题有很多重要的共享:
n/2/2/2
和n/3/3
可能是相同的。这个问题不太适合我的策略。A solution without indexing, and not based on Edward KMETT's.
I factor out common subtrees to a common parent (
f(n/4)
is shared betweenf(n/2)
andf(n/4)
, andf(n/6)
is shared betweenf(2)
andf(3)
). By saving them as a single variable in the parent, the calculation of the subtree is done once.The code doesn't easily extend to a general memoization function (at least, I wouldn't know how to do it), and you really have to think out how subproblems overlap, but the strategy should work for general multiple non-integer parameters. (I thought it up for two string parameters.)
The memo is discarded after each calculation. (Again, I was thinking about two string parameters.)
I don't know if this is more efficient than the other answers. Each lookup is technically only one or two steps ("Look at your child or your child's child"), but there might be a lot of extra memory use.
Edit: This solution isn't correct yet. The sharing is incomplete.Edit: It should be sharing subchildren properly now, but I realized that this problem has a lot of nontrivial sharing:
n/2/2/2
andn/3/3
might be the same. The problem is not a good fit for my strategy.