首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >缓存结果的更好模式

缓存结果的更好模式
EN

Stack Overflow用户
提问于 2013-03-17 09:44:44
回答 1查看 138关注 0票数 3

我现在多次运行类似的模式,这很容易出错(输入错误可以跳过一些缓存),而且对我来说看起来不太好。有没有更好的方式来写这样的东西呢?

代码语言:javascript
复制
sum_with_cache' result cache ((p1,p2,p3,p4):partitions) = let
        (cache_p1, sol1) = count_noncrossing' cache p1
        (cache_p2, sol2) = count_noncrossing' cache_p1 p2
        (cache_p3, sol3) = count_noncrossing' cache_p2 p3
        (cache_p4, sol4) = count_noncrossing' cache_p3 p4
    in sum_with_cache' (result+(sol1*sol2*sol3*sol4)) cache_p4 partitions

那么,基本上有N个操作可以更新缓存?

我也可以这样写:

代码语言:javascript
复制
process_with_cache' res cache _ [] = (cache, res)
process_with_cache' res cache f (x:xs) =
    let (new_cache, r) = f cache x
    in process_with_cache' (r:res) new_cache f xs
process_with_cache = process_with_cache' []

但这看起来也不是很干净。有没有更好的方式来写这段代码?

EN

回答 1

Stack Overflow用户

发布于 2013-03-17 11:24:06

另一个类似的模式是当您请求一系列命名的随机数时:

代码语言:javascript
复制
let (x, rng') = random rng''
    (y, rng)  = random rng'
in (x^2 + y^2, rng)

这正是使用state monad是正确的方法时:

代码语言:javascript
复制
import Control.Monad.State

对于所有(RandomGen g) => g类型的随机数生成器,都有一个状态单体State g,它隐式地线程状态:

代码语言:javascript
复制
do x <- state random
   y <- state random
   return (x^2 + y^2)

state函数只接受s -> (a, s)类型的函数,并将其转换为State s a类型的计算,在本例中:

代码语言:javascript
复制
state :: (RandomGen g) => (g -> (a, g)) -> State g a

您可以使用runStateevalStateexecState运行State计算

代码语言:javascript
复制
runState (liftA2 (\x y -> x^2 + y^2) (state random) (state random))
         (mkStdGen 0)
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15456732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档