Haskell 的蓄能器工厂

Accumulator factory in Haskell

现在,在我开始编程之旅时,我在理解基本概念时遇到了一些问题。这是一个与 Haskell 或一般功能范例相关的范例。

这里是蓄电池工厂问题的一般陈述,来自 http://rosettacode.org/wiki/Accumulator_factory

[Write a function that]

  • Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).

  • Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) (i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)

  • Generates functions that return the sum of every number ever passed to them, not just the most recent. (This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)

  • Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. (Follow your language's conventions here.)

  • Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. (No global variables or other such things.)

据我了解,关键是: “[...] 创建一个 [...] 生成 return 传递给它们的每个数字的总和的函数,而不仅仅是最近的。 (这需要一个状态来保存累积值,这反过来意味着纯函数式语言不能用于此任务。)"

我们可以在同一个网站上找到一个 Haskell 解决方案,它似乎与上面的引用所说的一样。

这里 http://rosettacode.org/wiki/Category:Haskell 据说Haskell是纯函数的

那么为什么会出现明显的矛盾呢?又或者没有矛盾,只是我缺乏理解?谢谢

Haskell 解决方案实际上并没有完全遵循挑战规则。特别是,它违反了函数 "Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program." 而不是返回真实函数的规则,它 returns 一个 ST 计算产生的函数本身产生更多 ST 计算。在 ST "state thread" 的上下文中,您可以创建和使用可变引用 (STRef)、数组和向量。但是,这种可变状态不可能 "leak" 在状态线程之外污染纯代码。