#目次
- Pure function
- Impure function
##Pure function
input
に対して指示された処理する。一番シンプルな例がabs(-1) #1
とか。
講義による定義は
their output depends only on their input parameter's values, and they do nothing in response to a call but compute a value
##Impure function
関数の中にはvalue
を返すこと以外の処理を行うものもある。そういった関数を__Impure function__と呼ぶ。value
を返すこと以外の処理をside effects
と呼ぶ。print
などがその典型的な例。
print(-2)
はシェル上では-2
とだけしか出ないが実際にはNone
というvalue
を返して-2
を表示しているだけ。
print(print(-2))
をシェルに投げ込んでみると、
-2
None
と出る。ここでは-2
がside effects
。
#print
とreturn
の違い
When Python executes a return statement, the function terminates immediately. If Python reaches the end of the function body without executing a return statement, it will automatically return None.
つまり
def what_prints():
print('Hello World!')
return 'Exiting this function.'
print('61A is awesome!')
>>> what_prints()
Hello World!
'Exiting this function.'
この解説動画がものすごく分かりやすく説明してくれているので必見。
#追記
以下の質問もnon-pure functionsの特徴を上手く指摘していたので備忘録として。
so when I was reviewing what we did in lab01, I came across the following:
When Python executes a return statement, the function terminates immediately. If Python reaches the end of the function body without executing a return statement, it will automatically return None.
However, unlike a return statement, when Python evaluates a print expression, the function does not terminate immediately.
Q1. does "If Python reaches the end of the function body without executing a return statement, it will automatically return None" mean if there's function that doesn't have a return statement in it always returns None, but we can't see it in the Python interpreter?
Q2. say we have the fizzbuzz function that we did in dis01,
def fizzbuzz(n):
i = 1
while i <= n:
if i % 3 == 0 and i % 5 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i)
i += 1
since this function doesn't have a return statement in it, if you run result = fizzbuzz(3)
the results will be shown but just typing in the variable like >>> result
will just show None
which you can't see in the interpreter. am I correct?
に対しての答えが:
Your answers to both your questions are correct, although for Q1 there's a fine point I want to make: a function that has a return statement can still return None, such as the following function:
def f():
if False:
return "this will never be returned"
One way to think about this is that there is an invisible return None at the end of every function ever.
You're correct about Q2, because print(result) when result is None is tantamount to print(None), which will indeed print None. If you're not convinced I encourage you to put the code in the interpreter and try it yourself.
確かに考えてみると
>>> def f():
... if False:
... return "this will be never returned"
...
>>> f()
>>> print(f())
None
##refs:
The Non-Pure Print Function