Lecture 24

Higher-order functions & lambda

MCS 260 Fall 2021
Emily Dumas

Reminders

  • Homework 8 due tomorrow at 10am
  • Midterm letter grades will be posted Wednesday
  • Project 3 will be announced this week
  • sum

    The built-in function sum(L) takes an iterable L and returns the sum of all its elements.

    Higher-order functions

    Previously (Lec 20): functions are values

    Functions can take other functions as arguments

    
            def dotwice(f):
                """Call the function f twice (with no arguments)"""
                f()
                f()
        

    A function that accepts function arguments is sometimes called a higher-order function.

    See dotwice.py.

    Example

    A function announce_call(f) that calls a given function f, but prints a message before and after.

    See announce.py.

    Example

    A function that loops from 0 to 100, but accepts a function to increment the value.

    See looper.py.

    Example

    A function nest(func,val,times) that applies function func a specified number of times to val i.e.

    • nest(f,x,3) should return the value of f(f(f(x)))
    • next(h,y,2) should return the value of h(h(y))

    See nest.py.

    Example

    A function repeat_until_acceptable(getval,testfn) that calls getval repeatedly until the return value is one for which testfn returns True.

    lambda

    In Python, you can create a function with no name using the syntax:

    
            lambda x: x*x    # param x, return value x*x
            lambda x,y: x-y  # params x and y, return value x-y
        

    lambda gives you the function object, so the value of

    
            lambda x,y: x-y
        

    is the same as the value of

    
            diff
        

    if you previously defined

    
            def diff(x,y):
                return x-y
        

    When to use lambda

    Functions definitely deserve names if they are used in several places, or if they are complicated.

    But lambda is good for simple functions used once, so the definition appears in the only place of use.

    Common use for lambda

    The built-in functions max, min, and list.sort accept a keyword argument key that is a function which is applied to elements before making comparisons.

    e.g. if L is a list of words, then max(L,key=len) is the longest word.

    References

    Revision history

    • 2021-10-18 Initial publication
    • 2021-10-19 Links to sample code