在函数式编程中关闭的地方 [英] The place of closures in functional programming
问题描述
我看过罗伯特·C·马丁的功能编程的演讲,什么?为什么?什么时候?
https://www.youtube.com/watch?v=7Zlp9rKHGD4
这次演讲的主要信息是一个状态在函数式编程中是不可接受的。
马丁走得更远,声称分配是'邪恶'。
所以...记住这个问题,我的问题是,函数式编程中的地方在哪里?
当函数代码中没有状态变量或没有变量时,创建和使用这种闭包(闭包不包含任何状态,任何变量)的主要原因是什么?关闭机制是否有用?
没有状态或变量(可能只有不可变的id),不需要引用当前的词法作用域没有什么可以改变的)?
在这种方法中,这足以使用类似Java的lambda机制,其中没有链接到当前词法作用域(这就是为什么变量必须是最终的)。
在一些资料中,闭包意味着必须具备功能语言元素。
可以关闭的词法作用域不需要可变就可以使用。只要考虑一下curried函数就可以了:
add = \a- - > \b - > a + b
add1 = add(1)
add3 = add(3)
[add1(0),add1(2),add3(2),add3(5)] // [1,2,5,8]
这里,内部的lamba关闭了 a
(或通过变量 a
,这不会因为不可变性而产生差异)。
函数式编程并非最终需要闭包,但局部变量也不是。尽管如此,他们都是非常好的想法。闭包允许对函数式编程的最重要任务(?)进行简单的表示:从抽象代码中动态创建具有专门行为的新函数。
I have watched the talk of Robert C Martin "Functional Programming; What? Why? When?" https://www.youtube.com/watch?v=7Zlp9rKHGD4
The main message of this talk is that a state is unacceptable in functional programming. Martin goes even further, claims that assigments are 'evil'.
So... keeping in mind this talk my question is, where is a place for closure in functional programming?
When there is no state or no variable in a functional code, what would be a main reason to create and use such closure (closure that does not enclose any state, any variable)? Is the closure mechanism useful?
Without a state or a variable, (maybe only with immutables ids), there is no need to reference to a current lexical scope (there is nothing that could be changed)?
In this approach, that is enough to use Java-like lambda mechanism, where there is no link to current lexical scope (that's why the variables have to be final).
In some sources, closures are meant to be a must have element of functional language.
A lexical scope that can be closed over does not need to be mutable to be useful. Just consider curried functions as an example:
add = \a -> \b -> a+b
add1 = add(1)
add3 = add(3)
[add1(0), add1(2), add3(2), add3(5)] // [1, 2, 5, 8]
Here, the inner lamba closes over the value of a
(or over the variable a
, which doesn't make a difference because of immutability).
Closures are not ultimately necessary for functional programming, but local variables are not either. Still, they're both very good ideas. Closures allow for a very simple notation of the most(?) important task of functional programming: to dynamically create new functions with specialised behaviour from an abstracted code.
这篇关于在函数式编程中关闭的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!