CSE 341�Section 4
Higher-Order Functions
Winter 2021
Today’s Agenda
CSE 341: Programming Languages
2
Homework 1 Recap &
Homework 2 due Friday 5 pm
Parameterized Variants
type ('a, 'b) tree = � Leaf of 'a �| Node of 'b * ('a, 'b) tree � * ('a, 'b) tree
What expressions could this variant type support, and what are their types?
Anonymous Functions
fun pattern -> expression
let name pattern = expression in name
What’s the difference? What can you do with one that you can’t do with the other?
Unnecessary Function Wrapping
What's the difference between the following two expressions?
(fun xs -> List.tl xs) vs. List.tl�
STYLE POINTS!
(if ex then true else false) vs. ex
Let’s practice! (Worksheet Q2 and Q3)
Higher-Order Functions
* debatable
Higher-order function idioms
fold, map, filter, etc.
Fold: Returns a “thing” that is the accumulation of the first argument applied to the third argument’s elements stored in the second argument.
let rec fold f a l =
match l with
[] -> a
| h::t -> f (fold f a t) h
Example:
fold (fun a b -> a + b) 0 [1;2;3] = 6
Higher-order function - Fold
let rec fold f a l =
match l with
[] -> a
| h::t -> f (fold f a t) h
('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
Higher-Order Function - Fold
Back to front!
No
Let’s practice! (Worksheet Q5)
Higher-Order Functions
Let’s look at an association list representation of a map and some operations (Emacs)
Association Lists
k1
v1
k2
v2
k3
v3
...
Closure-Based Representation
Closure-Based Representation
fn =>
...
k1
v1
m
fn =>
...
k2
v2
m’
fn =>
...
k3
v3
m’’
...
Does this look familiar?
Closure-Based Representation
fun ->
...
k1
v1
m
fun ->
...
k2
v2
m’
fun ->
...
k3
v3
m’’
...
k1
v1
k2
v2
k3
v3
...
Benefits of this representation