haskell - haskell 的蓄能器工厂

标签 haskell stateful

现在,在我开始编程之旅时,我在理解基本概念时遇到了一些问题。这是与 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.)

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

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

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

那么如何解释这个明显的矛盾呢?或者也许这并不矛盾,只是我缺乏一些理解?谢谢。

最佳答案

Haskell 解决方案实际上并不完全遵循挑战规则。特别是,它违反了函数“返回一个真正的函数,意味着您可以在任何可以使用您在程序文本中以普通方式定义的函数的地方使用的东西”的规则。它不返回实际函数,而是返回一个 ST 计算,该计算生成一个函数,该函数本身会生成更多 ST 计算。在 ST“状态线程”的上下文中,您可以创建和使用可变引用 (STRef)、数组和向量。但是,这种可变状态不可能“泄漏”到状态线程之外来污染纯代码。

关于haskell - haskell 的蓄能器工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33282863/

相关文章:

java - Ejb 3,消息驱动bean与有状态 session bean合作?

java - 如何创建有状态的 Web 服务?

dart - 将参数传递给 initState

haskell - 如何将 hackage 包包含到 Leksah 中

haskell - 如何使用 MinGW/MSYS 在 Windows 上安装 wxHaskell

xml - Haskell 对 XML 中的 Unicode 的态度是什么?

haskell - 在 Haskell 中导出任意函数

flutter - 停用和处置之间的区别?

haskell - 如何从支持某些 API 的函数返回非具体值?

java - 使用布局管理器进行状态策略