Difference between revisions of "Function"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
m (add Higher-order function)
(Added Basics sidebar)
 
(2 intermediate revisions by one user not shown)
Line 1: Line 1:
 
{{Sufficient-class}}
 
{{Sufficient-class}}
 
[[File:Function_Diagram.png|thumb|300px|A canonical function diagram that shows the input, output, and the function body. The name is visible, but the contents (the body) of the function are hidden.]]
 
[[File:Function_Diagram.png|thumb|300px|A canonical function diagram that shows the input, output, and the function body. The name is visible, but the contents (the body) of the function are hidden.]]
 
+
{{Basics sidebar}}
 
A '''function''' is a piece of code that accomplishes a specific task. It usually takes in ''argument(s)'' as input, does some processing, and ''returns'' a result. Once a function is written, it can be ''called'' over and over again.
 
A '''function''' is a piece of code that accomplishes a specific task. It usually takes in ''argument(s)'' as input, does some processing, and ''returns'' a result. Once a function is written, it can be ''called'' over and over again.
  
 
== Motivation ==
 
== Motivation ==
Functions take advantage of [[abstraction]]: we don't care how the function carries out its task, we just care that it gives us a correct result.
+
Functions take advantage of [[abstraction]]: we don't care how the function carries out its task; we just care that it gives us a correct result.
  
 
In addition, functions allow us to reuse code instead of rewriting it to work with different values.
 
In addition, functions allow us to reuse code instead of rewriting it to work with different values.
Line 15: Line 15:
 
*<code>add</code> always returns the sum of the arguments and has no side effects.
 
*<code>add</code> always returns the sum of the arguments and has no side effects.
 
*<code>square</code>
 
*<code>square</code>
 +
 +
<syntaxhighlight lang="python">
 +
def square(x):
 +
    return x * x
 +
</syntaxhighlight>
 +
 +
* A <code>def</code> [[Statement#def|statement]] is used to create the function with intrinsic name square and bind it to the name <code>square</code> in the current environment.
 +
* Following the intrinsic name is a list of ''formal parameters'' within the parentheses, the names that we will give the arguments to the function in a [[Expression#Call expressions|function call]]. In this case, we only have one formal parameter <code>x</code>.
 +
* Finally, we denote the expression whose value we output as the value of the function call using the '''<code>return</code> statement'''. In this example, the value of a function call to <code>square</code> will be the value of <code>x * x</code> evaluated in tho local frame created by that function call.
 +
* If a return statement is not present, a function will automatically output <code>None</code>.
  
 
== Non-pure function ==
 
== Non-pure function ==
Line 24: Line 34:
  
 
==== Functions that modify a variable in another frame ====
 
==== Functions that modify a variable in another frame ====
The following <code>get_a()</code> function modifies the variable <code>a</code> in the global frame:
+
The following <code>get_a()</code> function modifies the variable <code>a</code> in the global [[Frame|frame]]:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
 
a = 0
 
a = 0
Line 69: Line 79:
 
== Higher-order function ==
 
== Higher-order function ==
 
{{Main|Higher-order function}}
 
{{Main|Higher-order function}}
 
+
A higher-order function is a function that takes in functions as arguments and/or returns functions as output.
 
== Sources ==
 
== Sources ==
 
* http://www.cs.utah.edu/~germain/PPS/Topics/functions.html
 
* http://www.cs.utah.edu/~germain/PPS/Topics/functions.html

Latest revision as of 10:56, 9 July 2014

A canonical function diagram that shows the input, output, and the function body. The name is visible, but the contents (the body) of the function are hidden.

A function is a piece of code that accomplishes a specific task. It usually takes in argument(s) as input, does some processing, and returns a result. Once a function is written, it can be called over and over again.

Motivation

Functions take advantage of abstraction: we don't care how the function carries out its task; we just care that it gives us a correct result.

In addition, functions allow us to reuse code instead of rewriting it to work with different values.

Pure function

A pure function produces no effects other than returning a value. Its return value depends only on the inputs. Given the same arguments, it always returns the same value.

Examples

  • add always returns the sum of the arguments and has no side effects.
  • square
def square(x):
    return x * x
  • A def statement is used to create the function with intrinsic name square and bind it to the name square in the current environment.
  • Following the intrinsic name is a list of formal parameters within the parentheses, the names that we will give the arguments to the function in a function call. In this case, we only have one formal parameter x.
  • Finally, we denote the expression whose value we output as the value of the function call using the return statement. In this example, the value of a function call to square will be the value of x * x evaluated in tho local frame created by that function call.
  • If a return statement is not present, a function will automatically output None.

Non-pure function

A non-pure function or impure function produces a side effect (e.g., mutation, printing to screen). Its return value may depend on external state; when called multiple times with the same arguments, it may return different values.

Examples

print

The print function displays a value on the screen and returns None.

Functions that modify a variable in another frame

The following get_a() function modifies the variable a in the global frame:

a = 0
def get_a():
    global a
    a += 1
    return a - 1

The following tick function modifies the variable n in the countdown frame:

def countdown(n):
    def tick():
        nonlocal n
        n -= 1
        return n
    return tick

Functions that mutate an object in another frame

The following add_square function mutates lst in the global frame:

lst = []
def append_square(n):
    lst.append(n*n)

randint

randint returns a random number in the provided range, so the same function call may return different values. Example:

>>> from random import randint
>>> randint(0, 10)
0
>>> randint(0, 10)
6
>>> randint(0, 10)
7
>>> randint(0, 10)
2
>>> randint(0, 10)
10

Higher-order function

Main article: Higher-order function

A higher-order function is a function that takes in functions as arguments and/or returns functions as output.

Sources