CS61A - Lin Growing

Lecture 4 · Higher-Order Functions

On this page
  • higher-order function is a funtion that takes a function as an argument or return value.

If and call expressions

  • Conditional evaluation lets us handle values that would otherwise be undefined without raising an error.
  • Using a regular if statement
def real_sqrt(x):
	### return the real part of the square root of x ###
	if x >= 0:
		return sqrt(x)
	else:
		return 0 
  • Using a function
def if_(c, t, f):
	if c:
		return t
	else:
		return f
from math import sqrt
def real_sqrt(x):
	return if_(x >= 0, sqrt(x), 0)
	### 这里会先行evaluate () 内的函数,如果有错,则先于if_ 报错 ###

High order funtions

  • generalize the funtion

    • assert 3 > 2, ‘Math is broken’
    • If the condition is false, the assertion displays the error message that follows.An assertion and its error message
  • generalize the math

    • Before generalization:The implementation before generalization
    • After generalizationThe generalized implementation

Funtions as return values

def make_adder(n):
	def adder(k):
		return k + n
	return adder

Returning a function with make_adder

English translation · Read Chinese original