简体   繁体   English

如何保存函数的结果?

[英]How to save the results of a function?

Just a general question: 只是一个普遍的问题:

I am rather new to Haskell (and to programming in general, for that matter) and I would like to know how it is possible to save the results of a function no matter how often that function is executed. 我对Haskell(以及对此的一般编程)还不太陌生,并且我想知道无论该函数执行的频率如何,都可以保存该函数的结果。 When I execute my function, I want the result to be saved somewhere, so that no matter how often I call the function with different parameters, I have access to all the previous results. 当我执行函数时,我希望将结果保存在某个地方,这样无论我使用不同参数调用函数的频率如何,我都可以访问所有先前的结果。

Any help would be appreciated. 任何帮助,将不胜感激。

I suppose what you're asking is, how to memoise a function. 我想您要问的是如何记忆功能。 Memoisation means when a (possibly expensive) function has once been evaluated with some arguments x,y,z and is at some later point evaluated with the exact same arguments again, the processor won't actually need to do all the computation again but just look up the result in some sort of table. 记忆化意味着,一旦使用某个参数x,y,z对一个(可能是昂贵的)函数进行了评估x,y,z并在以后的某个时刻再次使用了完全相同的参数进行了评估,则处理器实际上不需要再次执行所有计算,而只是在某种表格中查找结果。

There are simple libraries for doing that. 有简单的库可以做到这一点。 With MemoTrie : MemoTrie

import Data.MemoTrie

f :: Int -> Int
f x = ... -- some expensive computation

fm :: Int -> Int
fm = memo f

Now if you call f 0 twice in a row, it will twice spend a long to to finish. 现在,如果连续两次调用f 0 ,它将花费两次很长时间才能完成。 OTOH, fm 0 will only take long the first time, the second time it'll give the result almost immediately. OTOH, fm 0第一次只会花费很长时间,第二次它将几乎立即给出结果。

If you know you only want to use f memoised, you can also define it this way right away: 如果您知道只想使用f memoised,也可以立即使用以下方式进行定义:

f :: Int -> Int
f = memo $ \x -> ...

Int -> Int is just an example signature. Int -> Int只是一个示例签名。 The result of such a function can have any type you desire, and the arguments can also be pretty much any “discrete” type (any integral number, tuples, strings...). 这样的函数的结果可以是您想要的任何类型,并且参数也可以是几乎任何“离散”类型(任何整数,元组,字符串...)。


MemoTrie , like most such libraries, will only store the results in RAM. 像大多数此类库一样, MemoTrie仅将结果存储在RAM中。 So when your program exists and you start it completely new, the memoised results will be gone and need to be computed anew, after all. 因此,当您的程序存在并且您完全重新启动它时,记录的结果将消失,并且毕竟需要重新计算。 Storing results persistently is more involved. 持续存储结果涉及更多。 I'm not aware of any library that does this in an automatic fashion. 我不知道任何以自动方式执行此操作的库。 What's a bit problematic is that the state of which arguments have already been tried is not really part of the Haskell semantics. 有点问题的是,已经尝试过参数的状态实际上并不是Haskell语义的一部分。

I have recently dabbled with a project that does something very related, though. 不过,我最近涉足的一个项目的工作非常相关。

https://github.com/leftaroundabout/lazy-hash https://github.com/leftaroundabout/lazy-hash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM