Higher Order Functions

Table of Contents

1. higher order funcitons

A function that takes in a function

Example

def double(x):
    return 2 * x

my_list = [1, 2, 7, -4]

print(list(map(double, my_list)))

Why create a variable when we only use it once…

def double(x):
    return 2 * x


print(list(map(double, [1, 2, 7, -4])))


why create a function name if we only use it once…

1.1. Anonymous Functions

functions with no names

lambda x : 2 * x

map(lambda x : 2 * x, [1, 2, 7, -4])

in racket…

;;racket
(lambda (x) (* 2 x))

;;typed/racket
(lambda ([x : Real]) : Real (* 2 x))

filter example

;;write a racket expresssion to return only

;; the elements in a list of strings longer than 4 chars

(filter (lambda ([str : String]) : Boolean (> (str-length str) 4)) ’(“hello’ ”world“ ”d"))

1.2. Having functions return functions

def f(x): def(g): return x + y return g

we have scopes that overlap in python

x is in scope within the def(g) but y is not in the scope within f(x)

addfive = f(5) -> addfive value is a function

print(addfive(17)) -> 22

addseven = f(7)

print(addfive(addseven(0))) -> 12

functiosn as values = “closures”

1.3. How to make high-order functions work

doesnt work in AAQZ 3 because names of values and functions are completley different

program -> [parser] -> AST -> [interp] -> Real number (in AAQZ 3)

To be able to pass functions into functions we need the interp to return a Value

Value

  • Real Number (in AAQZ4)
  • functions

Date: 2024-10-16 Wed 00:00

Author: Anthony Rossi

Created: 2024-10-18 Fri 16:09