简体   繁体   English

这种函数式编程优化叫什么?

[英]What is this functional programming optimization called?

Consider the following Haskell code for computing the nth Fibonacci number.考虑以下用于计算第 n 个斐波那契数的 Haskell 代码。

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)

This code is slow.这段代码很慢。 We can optimize it by refactoring to a helper function that computes "iteratively", by "storing" all the relevant data to compute the recurrence with in its arguments, along with a "counter" that tells us how long to compute for.我们可以通过将其“存储”所有相关数据以在其 arguments 中“存储”所有相关数据来计算递归,重构为“迭代”计算的帮助程序 function 以及告诉我们计算多长时间的“计数器”来优化它。

fastfib :: Int -> Int
fastfib n = helper 1 0 n
  where
    helper a _ 1 = a
    helper a b i = helper (a + b) a (i - 1)

It seems like this optimization could apply more broadly as well.似乎这种优化也可以更广泛地应用。 Does it have a name, in the functional programming community or elsewhere?它在函数式编程社区或其他地方有名字吗?

Yes, it's called accumulating parameter technique.是的,这叫累加参数技术。 (Here's one of my answers , about it). (这是我的答案之一,关于它)。

It's closely related to , tail-recursion-modulo-cons ("TRMC"), , hylomorphism s, folding , etc.它与tail-recursion-modulo-cons ("TRMC")、 hylomorphismfolding等密切相关。

Monoids enable the re-parenthesization Monoids 启用重新括号

a+(b+(c+...)) == (a+b)+(c+...) == ((a+b)+c)+...

which enables the accumulation.这使得积累。 TRMC (which came to be explicitly known in the context of Prolog) is the same, just with lists; TRMC (在 Prolog 的上下文中被明确地知道)是相同的,只是列表;

[a]++([b]++([c]++...)) == ([a]++[b])++([c]++...) == (([a]++[b])++[c])++...

and corecursion builds lists in top-down manner just like TRMC does. corecursion像 TRMC 一样以自上而下的方式构建列表。

The answer linked above contains a link to the technical report from 1974 by Friedman and Wise, which essentially talks about accumulation in the context of the + monoid, as an example.上面链接的答案包含指向弗里德曼和怀斯1974 年技术报告的链接,该报告本质上是在+幺半群的背景下讨论积累,例如。

There's no monoids in the Fibonacci example, but there's an accumulation of "knowledge" so to speak, as we go along from one Fibonacci number to the next.斐波那契示例中没有幺半群,但可以说是“知识”的积累,因为我们从一个斐波那契数到下一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM