Haskell和纯函数结果的记忆 [英] Haskell and memoization of pure function results

查看:105
本文介绍了Haskell和纯函数结果的记忆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

何时在GHC Haskell中自动记忆? 因此,纯函数总是为固定输入返回相同的值。也就是说,如果有足够的内存(问题1)并且开发人员是否有任何控制(问题2),Haskell(更确切地说是GHC)会自动缓存(记忆)这些结果吗?



GHC不做任何自动记忆功能,而且可能是一件好事,因为它会让空间复杂性更难以推理。此外,memoization通常不是一个非常可以解决的问题,因为它要求函数的参数对于所有类型(例如函数)都不可能实现的相等性是可比较的。

Haskell具有非严格的语义。 GHC或多或少地提供按需呼叫成本模式。尽管由于严格性分析器的原因,高优化级别下的懒惰评估开销并不是那么糟糕。

使用惰性评估在Haskell中实现记忆是非常容易的。尽管如此,请注意空间使用情况。

  fib'::(Integer  - > Integer) - >整数 - >整数
fib'f 0 = 0
fib'f 1 = 1
fib'f n | n> 1 =(f(n-1))+((f(n-2))

slow_fib :: Integer - >整数
slow_fib = fib'slow_fib

fibs :: [Integer]
fibs = map(fib'memo_fib)[0 ..]

memo_fib :: Integer - >整数
memo_fib n = fibs !! n

这实际上并不是那么快,而且是空间泄漏,但它捕捉到了一般想法。您可以在Haskell wiki上详细了解


Possible Duplicate:
When is memoization automatic in GHC Haskell?

As a consequence, pure function always returns the same value for a fixed input. That said, does Haskell (more precisely GHC) automatically cache (memoize) these results if there is enough memory (question 1) and does developer have any control on it (question 2)?

解决方案

I voted to close, but short answer:

GHC does not do any automatic memoization of functions, and that is probably a good thing because it would make space complexity even harder to reason about. Also, memoization is not in general a very solvable problem, since it requires the argument of the function be comparable for equality which is not really possible for all types (for example, functions).

Haskell has non-strict semantics. GHC provides a, more or less, call by need cost model. Although the overhead of lazy evaluation at high optimization levels is not that bad because of the strictness analyzer.

It is very easy to implement memoization in Haskell using lazy evaluation. Be careful about space usage though.

fib' :: (Integer -> Integer) -> Integer -> Integer
fib' f 0 = 0
fib' f 1 = 1
fib' f n | n > 1 = (f (n - 1)) + ((f (n - 2))

slow_fib :: Integer -> Integer
slow_fib = fib' slow_fib

fibs :: [Integer]
fibs = map (fib' memo_fib) [0..] 

memo_fib :: Integer -> Integer
memo_fib n = fibs !! n

This is actually not that fast, and is a space leak, but captures the general idea. You can learn more on the Haskell wiki.

这篇关于Haskell和纯函数结果的记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆