功能编程:副作用 [英] Functional Programming: Side Effects
问题描述
def isPrime(n):
k = 2
while k < n:
如果n%k == 0:
返回False
k + = 1
返回True
文字说上述函数有局部副作用,我不明白。我看到变量k正在改变,我不明白它会带来什么坏处。
有人可以给出一个明显的不良副作用的例子,以及如何通过函数式编程避免它?
您所指的文本是正确的,副作用。
并不是说这是一件坏事。这只是功能编程。在纯粹的函数式编程语言中,您将以递归方式编写循环,无需更改变量。
写这样的函数(没有可观察到的副作用)是任何语言的一个很好的练习,它只是一种功能性编程。
编辑:现在我看到您对不良副作用的评论。我不会说副作用不好。在大多数主流语言中,没有它们就很难进行编程,我认为很多程序员都会考虑副作用。但是在大型软件项目中,过度依赖副作用会让你的生活变得非常悲惨。 这是一个很好的例子,涉及到单身人士(导致副作用的最终方式)
在一种禁止副作用的语言中,作为程序员的你和作为编译器的人都不会感到惊讶。纯函数代码更易于分析和并行化,并且至少在理论上更容易被编译器优化。
Most tutorials/articles/books talk about side effects when presenting functional programming. Take this Python code:
def isPrime(n):
k = 2
while k < n:
if n % k == 0:
return False
k += 1
return True
The text says that the above function has local side effects, and I don't understand that. I see that the variable "k" is changing, I don't understand what bad comes out of it.
Can someone please give a clear example of bad side effect, and how it is avoided by functional programming?
The text you're referring to is right, changing a local variable is considered a side effect.
It doesn't say that this is a bad thing necessarily. It is just not functional programming. In pure functional programming languages you would write the loop in a recursive way, eliminating the need for changing variables.
Writing functions like these (that have no observable side effects) is a fine practice in any language, it is just not functional programming.
Edit: Now I see your remark about "bad" side effects. I would not say that side effects are bad. In most mainstream languages, it is hard to program without them, and I think that many programmers think in terms of side effects. But in large software projects, relying too much on side effects can make your life pretty miserable. Here's a nice example involving singletons (the ultimate way to cause side effects)
In a language that forbids side effects, there are less surprises for you as a programmer, but also for the compiler. Pure functional code is easier to analyze and paralellize, and is, at least theoretically, easier to optimize by the compiler.
这篇关于功能编程:副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!