副作用是好事吗? [英] Are side effects a good thing?

查看:250
本文介绍了副作用是好事吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这个词相当贬义。因此,我对维基百科中的两句话大加赞赏:

I feel the term rather pejorative. Hence, I am flabbergasted by the two sentences in Wikipedia:


命令式编程以
为名,使用副作用来制作
程序功能。功能
编程反过来以其
副作用最小化而闻名。 [1]

因为我有点数学偏见,后者听起来很好。什么是副作用的论据?他们是指失去控制权或接受不确定性吗?他们是好事吗?

Since I am somewhat Math-biased, the latter sounds excellent. What are the arguments for side-effects? Do they mean the loss of control or the acceptance of uncertainty? Are they a good thing?

推荐答案

每隔一段时间我都会看到一个关于SO的问题,这迫使我花费半个小时编辑维基百科的文章真的很差。这篇文章现在只是比较糟糕。在关于你的问题的部分,我写了如下:

Every so often I see a question on SO which forces me to spend half an hour editing a really bad Wikipedia article. The article is now only moderately bad. In the part that bears on your question, I wrote as follows:


在计算机科学中,函数或表达式被认为具有<强副作用如果除了产生一个值之外,还会修改某些状态或与调用函数或外部世界进行可观察的交互。例如,一个函数可能会修改全局变量或静态变量,修改其中的一个参数,引发异常,将数据写入显示或文件,读取数据,调用其他副作用函数或发射导弹。在存在副作用的情况下,程序的行为取决于过去的历史;也就是评估顺序。因为理解一个有效的程序需要考虑所有可能的历史,所以副作用通常会使程序难以理解。

In computer science, a function or expression is said to have a side effect if, in addition to producing a value, it also modifies some state or has an observable interaction with calling functions or the outside world. For example, a function might modify a global or a static variable, modify one of its arguments, raise an exception, write data to a display or file, read data, call other side-effecting functions, or launch missiles. In the presence of side effects, a program's behavior depends on past history; that is, the order of evaluation matters. Because understanding an effectful program requires thinking about all possible histories, side effects often make a program harder to understand.

副作用对于使程序与外部交互至关重要世界(人们,文件系统,网络上的其他计算机)。但是,使用副作用的程度取决于编程范例。命令式编程以不受控制的,滥用副作用而闻名。在函数式编程中,副作用很少使用。诸如Standard ML和Scheme之类的函数式语言不会限制副作用,但程序员习惯避免这些副作用。功能语言Haskell用静态类型系统来限制副作用;只有产生IO类型结果的函数会产生副作用。

Side effects are essential to enable a program to interact with the outside world (people, filesystems, other computers on networks). But the degree to which side effects are used depends on the programming paradigm. Imperative programming is known for uncontrolled, promiscuous use of side effects. In functional programming, side effects are rarely used. Functional languages such as Standard ML and Scheme do not restrict side effects, but it is customary for programmers to avoid them. The functional language Haskell restricts side effects with a static type system; only a function that produces a result of IO type can have side effects.

这篇关于副作用是好事吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆