我现在多次运行类似的模式,这很容易出错(输入错误可以跳过一些缓存),而且对我来说看起来不太好。有没有更好的方式来写这样的东西呢?
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个操作可以更新缓存?
我也可以这样写:
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' []但这看起来也不是很干净。有没有更好的方式来写这段代码?
发布于 2013-03-17 11:24:06
另一个类似的模式是当您请求一系列命名的随机数时:
let (x, rng') = random rng''
(y, rng) = random rng'
in (x^2 + y^2, rng)这正是使用state monad是正确的方法时:
import Control.Monad.State对于所有(RandomGen g) => g类型的随机数生成器,都有一个状态单体State g,它隐式地线程状态:
do x <- state random
y <- state random
return (x^2 + y^2)state函数只接受s -> (a, s)类型的函数,并将其转换为State s a类型的计算,在本例中:
state :: (RandomGen g) => (g -> (a, g)) -> State g a您可以使用runState、evalState或execState运行State计算
runState (liftA2 (\x y -> x^2 + y^2) (state random) (state random))
(mkStdGen 0)https://stackoverflow.com/questions/15456732
复制相似问题