【发布时间】:2013-11-30 09:09:12
【问题描述】:
答案等于side effects 的定义。
到目前为止,我还没有找到准确的答案。 python 文档说:
Functional style discourages functions with side effects that modify internal state or make other changes that aren’t visible in the function’s return value.
什么是modify internal state 和make other changes that aren’t visible...?
将变量绑定到对象(只是绑定,而不是修改)是否意味着没有副作用?例如a=1或a=[1,2,3]或a,b=1,2。
这里有 4 个函数。它们都没有副作用吗?为什么?
注意,假设参数n 必须是int 对象。
def purefunc1(n):
def getn(n):
return [1,2,3,4,5][:n-1],[1,2,3,4,5][:n]
def addn(fir,sec,thd):
return fir+sec+thd
return addn(getn(n)[0],['HEY'],getn(n)[1])
def purefunc2(n):
def getn(n):
#bind
arr=[1,2,3,4,5]
return arr[:n-1],arr[:n]
def addn(fir=[],sec=[],thd=[]):
return fir+sec+thd
#bind
arg1,arg3=getn(n)
return addn(arg1,['HEY'],arg3)
def purefunc3(n):
arr=[1,2,3,4,5]
def getn(n):
#closure 'arr'
return arr[:n-1],arr[:n]
def addn(fir=[],sec=[],thd=[]):
return fir+sec+thd
#bind
arg1,arg3=getn(n)
return addn(arg1,['HEY'],arg3)
def purefunc4(n):
def arr():
return [1,2,3,4,5]
def getn(n):
#closure
return arr()[:n-1],arr()[:n]
def addn(fir=[],sec=[],thd=[]):
return fir+sec+thd
#bind
arg1,arg3=getn(n)
return addn(arg1,['HEY'],arg3)
print (purefunc1(3))
print (purefunc2(3))
print (purefunc3(3))
print (purefunc4(3))
我的猜测:purefunc1 没有副作用。但我不知道下面的纯函数*。
输出是:
[1, 2, 'HEY', 1, 2, 3]
[1, 2, 'HEY', 1, 2, 3]
[1, 2, 'HEY', 1, 2, 3]
[1, 2, 'HEY', 1, 2, 3]
如果你问为什么存在这么奇怪的函数,答案是它只是为了方便。真正的功能是复杂的。不过有兴趣的可以click here看看ieval这个函数有没有副作用。
提前谢谢大家。
【问题讨论】:
-
来自关于副作用的 wiki 页面:“在存在副作用的情况下,程序的行为取决于历史;也就是说,评估的顺序很重要。理解和调试具有副作用的函数需要了解上下文及其可能的历史。或来自程序员:programmers.stackexchange.com/questions/40297/…"
标签: python functional-programming