















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
















Standard Description: This summary covers roughly the same material as lecture and section. It can help to read about the material in a narrative style and to have the material for an entire unit of the course in a single document, especially when reviewing the material later. Please report errors in these notes, even typos. This summary is not a sufficient substitute for attending class, reading the associated code, etc.
Introduction and Some Terms...................................... 1
Taking Functions as Arguments..................................... 2
Polymorphic Types and Functions as Arguments.......................... 3
Anonymous functions............................................ 4
Unnecessary Function Wrapping.................................... 4
Maps and filters............................................... 5
Returning functions............................................. 6
Not just for numbers and lists...................................... 6
Lexical Scope................................................. 6
Environments and Closures........................................ 7
(Silly) Examples Including Higher-Order Functions........................ 8
Why Lexical Scope............................................. 8
Passing Closures to Iterators Like Filter............................... 9
Fold and More Closure Examples.................................... 10
Another Closure Idiom: Combining Functions............................ 11
Another Closure Idiom: Currying and Partial Application.................... 12
The Value Restriction........................................... 14
Mutation via ML References....................................... 15
Another Closure Idiom: Callbacks................................... 15
Optional: Another Closure Idiom: Abstract Data Types..................... 16
Optional: Closures in Other Languages................................ 18
Optional: Closures in Java using Objects and Interfaces..................... 19
Optional: Closures in C Using Explicit Environments....................... 21
Standard-Library Documentation.................................... 23
This unit focuses on first-class functions and function closures. By “first-class” we mean that functions can be computed, passed, stored, etc. wherever other values can be computed, passed, stored, etc. As examples, we can pass them to functions, return them from functions, put them in pairs, have them be part of the data a datatype constructor carries, etc. “Function closures” refers to functions that use variables defined outside of them, which makes first-class functions much more powerful, as we will see after starting with simpler
first-class functions that do not use this ability. The term higher-order function just refers to a function that takes or returns other functions.
Terms like first-class functions, function closures, and higher-order functions are often confused with each other or considered synonyms. Because so much of the world is not careful with these terms, we will not be too worried about them either. But the idea of first-class functions and the idea of function closures really are distinct concepts that we often use together to write elegant, reusable code. For that reason, we will delay the idea of closures, so we can introduce it as a separate concept.
There is an even more general term, functional programming. This term also is often used imprecisely to refer to several distinct concepts. The two most important and most common are:
There are other things that are also considered related to functional programming:
An obvious related question is “what makes a programming language a functional language?” Your instructor has come to the conclusion this is not a question for which there is a precise answer and barely makes sense as a question. But one could say that a functional language is one where writing in a functional style (as described above) is more convenient, more natural, and more common than programming in other styles. At a minimum, you need good support for immutable data, first-class functions, and function closures. More and more we are seeing new languages that provide such support but also provide good support for other styles, like object-oriented programming, which we will study some toward the end of the course.
The most common use of first-class functions is passing them as arguments to other functions, so we motivate this use first.
Here is a first example of a function that takes another function:
fun n_times (f,n,x) = if n= then x else f (n_times(f,n-1,x))
We can tell the argument f is a function because the last line calls f with an argument. What n_times does is compute f(f(...(f(x)))) where the number of calls to f is n. That is a genuinely useful helper function to have around. For example, here are 3 different uses of it:
There is no reason that a function like triple that is passed to another function like n_times needs to be defined at top-level. As usual, it is better style to define such functions locally if they are needed only locally. So we could write:
fun triple_n_times (n,x) = let fun triple x = 3*x in n_times(triple,n,x) end
In fact, we could give the triple function an even smaller scope: we need it only as the first argument to n_times, so we could have a let-expression there that evaluates to the triple function:
fun triple_n_times (n,x) = n_times((let fun triple y = 3*y in triple end), n, x)
Notice that in this example, which is actually poor style, we need to have the let-expression “return” triple since, as always, a let-expression produces the result of the expression between in and end. In this case, we simply look up triple in the environment, and the resulting function is the value that we then pass as the first argument to n_times.
ML has a much more concise way to define functions right where you use them, as in this final, best version:
fun triple_n_times (n,x) = n_times((fn y => 3*y), n, x)
This code defines an anonymous function fn y => 3y. It is a function that takes an argument y and has body 3y. The fn is a keyword and => (not =) is also part of the syntax. We never gave the function a name (it is anonymous, see?), which is convenient because we did not need one. We just wanted to pass a function to n_times, and in the body of n_times, this function is bound to f.
It is common to use anonymous functions as arguments to other functions. Moreover, you can put an anonymous function anywhere you can put an expression — it simply is a value, the function itself. The only thing you cannot do with an anonymous function is recursion, exactly because you have no name to use for the recursive call. In such cases, you need to use a fun binding as before, and fun bindings must be in let-expressions or at top-level.
For non-recursive functions, you could use anonymous functions with val bindings instead of a fun binding. For example, these two bindings are exactly the same thing:
fun increment x = x + 1 val increment = fn x => x+
They both bind increment to a value that is a function that returns its argument plus 1. So function-bindings are almost syntactic sugar, but they support recursion, which is essential.
While anonymous functions are incredibly convenient, there is one poor idiom where they get used for no good reason. Consider:
fun nth_tail_poor (n,x) = n_times((fn y => tl y), n, x)
What is fn y => tl y? It is a function that returns the list-tail of its argument. But there is al- ready a variable bound to a function that does the exact same thing: tl! In general, there is no rea- son to write fn x => f x when we can just use f. This is analogous to the beginner’s habit of writing if x then true else false instead of x. Just do this:
fun nth_tail (n,x) = n_times(tl, n, x)
We now consider a very useful higher-order function over lists:
fun map (f,xs) = case xs of [] => [] | x::xs’ => (f x)::(map(f,xs’))
The map function takes a list and a function f and produces a new list by applying f to each element of the list. Here are two example uses:
val x1 = map (increment, [4,8,12,16]) (* answer: [5,9,13,17] ) val x2 = map (hd, [[1,2],[3,4],[5,6,7]]) ( answer: [1,3,5] *)
The type of map is illuminating: (’a -> ’b) * ’a list -> ’b list. You can pass map any kind of list you want, but the argument type of f must be the element type of the list (they are both ’a). But the return type of f can be a different type ’b. The resulting list is a ’b list. For x1, both ’a and ’b are instantiated with int. For x2, ’a is int list and ’b is int.
The ML standard library provides a very similar function List.map, but it is defined in a curried form, a topic we will discuss later in this unit.
The definition and use of map is an incredibly important idiom even though our particular example is simple. We could have easily written a recursive function over lists of integers that incremented all the elements, but instead we divided the work into two parts: The map implementer knew how to traverse a recursive data structure, in this case a list. The map client knew what to do with the data there, in this case increment each number. You could imagine either of these tasks — traversing a complicated piece of data or doing some calculation for each of the pieces — being vastly more complicated and best done by different developers without making assumptions about the other task. That is exactly what writing map as a helper function that takes a function lets us do.
Here is a second very useful higher-order function for lists. It takes a function of type ’a -> bool and an ’a list and returns the ’a list containing only the elements of the input list for which the function returns true:
fun filter (f,xs) = case xs of [] => [] | x::xs’ => if f x then x::(filter (f,xs’)) else filter (f,xs’)
Here is an example use that assumes the list elements are pairs with second component of type int; it returns the list elements where the second component is even:
even more crucial to get the semantics right. This is probably the most subtle and important concept in the entire course, so go slowly and read carefully.
The body of a function is evaluated in the environment where the function is defined, not the environment where the function is called. Here is a very simple example to demonstrate the difference:
val x = 1 fun f y = x + y val x = 2 val y = 3 val z = f (x+y)
In this example, f is bound to a function that takes an argument y. Its body also looks up x in the environment where f was defined. Hence this function always increments its argument since the environment at the definition maps x to 1. Later we have a different environment where f maps to this function, x maps to 2, y maps to 3, and we make the call f x. Here is how evaluation proceeds:
Notice the argument was evaluated in the current environment (producing 5), but the function body was evaluated in the “old” environment. We discuss below why this semantics is desirable, but first we define this semantics more precisely and understand the semantics with additional silly examples that use higher-order functions.
This semantics is called lexical scope. The alternate, inferior semantics where you use the current environment (which would produce 7 in the above example) is called dynamic scope.
We have said that functions are values, but we have not been precise about what that value exactly is. We now explain that a function value has two parts, the code for the function (obviously) and the environment that was current when we created the function. These two parts really do form a “pair” but we put “pair” in quotation marks because it is not an ML pair, just something with two parts. You cannot access the parts of the “pair” separately; all you can do is call the function. This call uses both parts because it evaluates the code part using the environment part.
This “pair” is called a function closure or just closure. The reason is that while the code itself can have free variables (variables that are not bound inside the code so they need to be bound by some outer environment), the closure carries with it an environment that provides all these bindings. So the closure overall is “closed” — it has everything it needs to produce a function result given a function argument.
In the example above, the binding fun f y = x + y bound f to a closure. The code part is the function fn y => x + y and the environment part maps x to 1. Therefore, any call to this closure will return y+1.
Lexical scope and closures get more interesting when we have higher-order functions, but the semantics already described will lead us to the right answers.
Example 1:
val x = 1 fun f y = let val x = y+ in fn z => x + y + z end val x = 3 val g = f 4 val y = 5 val z = g 6
Here, f is bound to a closure where the environment part maps x to 1. So when we later evaluate f 4, we evaluate let val x = y + 1 in fn z => x + y + z end in an environment where x maps to 1 extended to map y to 4. But then due to the let-binding we shadow x so we evaluate fn z => x + y + z in an environment where x maps to 5 and y maps to 4. How do we evaluate a function like fn z => x + y + z? We create a closure with the current environment. So f 4 returns a closure that, when called, will always add 9 to its argument, no matter what the environment is at any call-site. Hence, in the last line of the example, z will be bound to 15.
Example 2:
fun f g = let val x = 3 in g 2 end val x = 4 fun h y = x + y val z = f h
In this example, f is bound to a closure that takes another function g as an argument and returns the result of g 2. The closure bound to h always adds 4 to its argument because the argument is y, the body is x+y, and the function is defined in an environment where x maps to 4. So in the last line, z will be bound to
While lexical scope and higher-order functions take some getting used to, decades of experience make clear that this semantics is what we want. Much of the rest of this section will describe various widespread idioms that are powerful and that rely on lexical scope.
fun allShorterThan2 (xs,s) = let val i = String.size s in filter(fn x => String.size x < i, xs) end
Both these functions take a list of strings xs and a string s and return a list containing only the strings in xs that are shorter than s. And they both use closures, to look up s or i when the anonymous functions get called. The second one is more complicated but a bit more efficient: The first one recomputes String.size s once per element in xs (because filter calls its function argument this many times and the body evaluates String.size s each time). The second one “precomputes” String.size s and binds it to a variable i available to the function fn x => String.size x < i.
Beyond map and filter, a third incredibly useful higher-order function is fold, which can have several slightly different definitions and is also known by names such as reduce and inject. Here is one common definition:
fun fold (f,acc,xs) = case xs of [] => acc | x::xs’ => fold (f, f(acc,x), xs’)
fold takes an “initial answer” acc and uses f to “combine” acc and the first element of the list, using this as the new “initial answer” for “folding” over the rest of the list. We can use fold to take care of iterating over a list while we provide some function that expresses how to combine elements. For example, to sum the elements in a list foo, we can do:
fold ((fn (x,y) => x+y), 0, foo)
As with map and filter, much of fold’s power comes from clients passing closures that can have “private fields” (in the form of variable bindings) for keeping data they want to consult. Here are two examples. The first counts how many elements are in some integer range. The second checks if all elements are strings shorter than some other string’s length.
fun numberInRange (xs,lo,hi) = fold ((fn (x,y) => x + (if y >= lo andalso y <= hi then 1 else 0)), 0, xs)
fun areAllShorter (xs,s) = let val i = String.size s in fold((fn (x,y) => x andalso String.size y < i), true, xs) end
This pattern of splitting the recursive traversal (fold or map) from the data-processing done on the elements (the closures passed in) is fundamental. In our examples, both parts are so easy we could just do the whole
thing together in a few simple lines. More generally, we may have a very complicated set of data structures to traverse or we may have very involved data processing to do. It is good to separate these concerns so that the programming problems can be solved separately.
Function composition
When we program with lots of functions, it is useful to create new functions that are just combinations of other functions. You have probably done similar things in mathematics, such as when you compose two functions. For example, here is a function that does exactly function composition:
fun compose (f,g) = fn x => f (g x)
It takes two functions f and g and returns a function that applies its argument to g and makes that the argument to f. Crucially, the code fn x => f (g x) uses the f and g in the environment where it was defined. Notice the type of compose is inferred to be (’a -> ’b) * (’c -> ’a) -> ’c -> ’b, which is equivalent to what you might write: (’b -> ’c) * (’a -> ’b) -> (’a -> ’c) since the two types simply use different type-variable names consistently.
As a cute and convenient library function, the ML library defines the infix operator o as function composition, just like in math. So instead of writing:
fun sqrt_of_abs i = Math.sqrt(Real.fromInt (abs i))
you could write:
fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i
But this second version makes clearer that we can just use function-composition to create a function that we bind to a variable with a val-binding, as in this third version:
val sqrt_of_abs = Math.sqrt o Real.fromInt o abs
While all three versions are fairly readable, the first one does not immediately indicate to the reader that sqrt_of_abs is just the composition of other functions.
The Pipeline Operator
In functional programming, it is very common to compose other functions to create larger ones, so it makes sense to define convenient syntax for it. While the third version above is concise, it, like function composition in mathematics, has the strange-to-many-programmers property that the computation proceeds from right- to-left: “Take the absolute value, convert it to a real, and compute the square root” may be easier to understand than, “Take the square root of the conversion to real of the absolute value.”
We can define convenient syntax for left-to-right as well. Let’s first define our own infix operator that lets us put the function to the right of the argument we are calling it with:
infix |> (* tells the parser |> is a function that appears between its two arguments *) fun x |> f = f x
fun fold f = fn acc => fn xs => case xs of [] => acc | x::xs’ => fold f (f(acc,x)) xs’
Now we could use this fold to define a function that sums a list elements like this:
fun sum1 xs = fold (fn (x,y) => x+y) 0 xs
But that is unnecessarily complicated compared to just using partial application:
val sum2 = fold (fn (x,y) => x+y) 0
The convenience of partial application is why many iterators in ML’s standard library use currying with the function they take as the first argument. For example, the types of all these functions use currying:
val List.map = fn : (’a -> ’b) -> ’a list -> ’b list val List.filter = fn : (’a -> bool) -> ’a list -> ’a list val List.foldl = fn : (’a * ’b -> ’b) -> ’b -> ’a list -> ’b
As an example, List.foldl((fn (x,y) => x+y), 0, [3,4,5]) does not type-check because List.foldl expects a ’a * ’b -> ’b function, not a triple. The correct call is List.foldl (fn (x,y) => x+y) 0 [3,4,5], which calls List.foldl with a function, which returns a closure and so on.
There is syntactic sugar for defining curried functions; you can just separate the conceptual arguments by spaces rather than using anonymous functions. So the better style for our fold function would be:
fun fold f acc xs = case xs of [] => acc | x::xs’ => fold f (f(acc,x)) xs’
Another useful curried function is List.exists, which we use in the callback example below. These library functions are easy to implement ourselves, so we should understand they are not fancy:
fun exists predicate xs = case xs of [] => false | x::xs’ => predicate x orelse exists predicate xs’
Currying in General
While currying and partial application are great for higher-order functions, they are great in general too. They work for any multi-argument function and partial application can also be surprisingly convenient. In this example, both zip and range are defined with currying and countup partially applies range. The add_numbers function turns the list [v1,v2,...,vn] into [(1,v1),(2,v2),...,(n,vn)].
fun zip xs ys = case (xs,ys) of ([],[]) => [] | (x::xs’,y::ys’) => (x,y) :: (zip xs’ ys’) | _ => raise Empty
fun range i j = if i > j then [] else i :: range (i+1) j
val countup = range 1
fun add_numbers xs = zip (countup (length xs)) xs
Combining Functions to Curry and Uncurry Other Functions
Sometimes functions are curried but the arguments are not in the order you want for a partial application. Or sometimes a function is curried when you want it to use tuples or vice-versa. Fortunately our earlier idiom of combining functions can take functions using one approach and produce functions using another:
fun other_curry1 f = fn x => fn y => f y x fun other_curry2 f x y = f y x fun curry f x y = f (x,y) fun uncurry f (x,y) = f x y
Looking at the types of these functions can help you understand what they do. As an aside, the types are also fascinating because if you pronounce -> as “implies” and * as “and”, the types of all these functions are logical tautologies.
Efficiency
Finally, you might wonder which is faster, currying or tupling. It almost never matters; they both do work proportional to the number of conceptual arguments, which is typically quite small. For the performance- critical functions in your software, it might matter to pick the faster way. In the version of the ML compiler we are using, tupling happens to be faster. In widely used implementations of OCaml, Haskell, and F#, curried functions are faster so they are the standard way to define multi-argument functions in those languages.
Once you have learned currying and partial application, you might try to use it to create a polymorphic function. Unfortunately, certain uses, such as these, do not work in ML:
val mapSome = List.map SOME (turn [v1,v2,...,vn] into [SOME v1, SOME v2, ..., SOME vn]) val pairIt = List.map (fn x => (x,x)) (turn [v1,v2,...,vn] into [(v1,v1),(v2,v2),...,(vn,vn)])
Given what we have learned so far, there is no reason why this should not work, especially since all these functions do work:
fun mapSome xs = List.map SOME xs val mapSome = fn xs => List.map SOME xs val pairIt : int list -> (int * int) list = List.map (fn x => (x,x)) val incrementIt = List.map (fn x => x+1)
The reason is called the value restriction and it is sometimes annoying. It is in the language for good reason: without it, the type-checker might allow some code to break the type system. This can happen only with code that is using mutation and the code above is not, but the type-checker does not know that.
The simplest approach is to ignore this issue until you get a warning/error about the value restriction. When you do, turn the val-binding back into a fun-binding like in the first example above of what works.
When we study type inference in the next unit, we will discuss the value restriction in a little more detail.
Our example uses the idea that callbacks should be called when a key on the keyboard is pressed. We will pass the callbacks an int that encodes which key it was. Our interface just needs a way to register callbacks. (In a real library, you might also want a way to unregister them.)
val onKeyEvent : (int -> unit) -> unit
Clients will pass a function of type int -> unit that, when called later with an int, will do whatever they want. To implement this function, we just use a reference that holds a list of the callbacks. Then when an event actually occurs, we assume the function onEvent is called and it calls each callback in the list:
val cbs : (int -> unit) list ref = ref [] fun onKeyEvent f = cbs := f::(!cbs) (* The only "public" binding *) fun onEvent i = let fun loop fs = case fs of [] => () | f::fs’ => (f i; loop fs’) in loop (!cbs) end
Most importantly, the type of onKeyEvent places no restriction on what extra data a callback can access when it is called. Here are different clients (calls to onKeyEvent) that use different bindings of different types in their environment. (The val _ = e idiom is common for executing an expression just for its side-effect, in this case registering a callback.)
val timesPressed = ref 0 val _ = onKeyEvent (fn _ => timesPressed := (!timesPressed) + 1)
fun printIfPressed i = onKeyEvent (fn j => if i=j then print ("you pressed " ^ Int.toString i ^ "\n") else ())
val _ = printIfPressed 4 val _ = printIfPressed 11 val _ = printIfPressed 23
This last closure idiom we will consider is the fanciest and most subtle. It is not the sort of thing programmers typically do — there is usually a simpler way to do it in a modern programming language. It is included as an advanced example to demonstrate that a record of closures that have the same environment is a lot like an object in object-oriented programming: the functions are methods and the bindings in the environment are private fields and methods. There are no new language features here, just lexical scope. It suggests (correctly) that functional programming and object-oriented programming are more similar than they might first appear (a topic we will revisit later in the course; there are also important differences).
The key to an abstract data type (ADT) is requiring clients to use it via a collection of functions rather than directly accessing its private implementation. Thanks to this abstraction, we can later change how the data type is implemented without changing how it behaves for clients. In an object-oriented language, you might implement an ADT by defining a class with all private fields (inaccessible to clients) and some public
methods (the interface with clients). We can do the same thing in ML with a record of closures; the variables that the closures use from the environment correspond to the private fields.
As an example, consider an implementation of a set of integers that supports creating a new bigger set and seeing if an integer is in a set. Our sets are mutation-free in the sense that adding an integer to a set produces a new, different set. (We could just as easily define a mutable version using ML’s references.) In ML, we could define a type that describes our interface:
datatype set = S of { insert : int -> set, member : int -> bool, size : unit -> int }
Roughly speaking, a set is a record with three fields, each of which holds a function. It would be simpler to write:
type set = { insert : int -> set, member : int -> bool, size : unit -> int }
but this does not work in ML because type bindings cannot be recursive. So we have to deal with the mild inconvenience of having a constructor S around our record of functions defining a set even though sets are each-of types, not one-of types. Notice we are not using any new types or features; we simply have a type describing a record with fields named insert, member, and size, each of which holds a function.
Once we have an empty set, we can use its insert field to create a one-element set, and then use that set’s insert field to create a two-element set, and so on. So the only other thing our interface needs is a binding like this:
val empty_set = ... : set
Before implementing this interface, let’s see how a client might use it (many of the parentheses are optional but may help understand the code):
fun use_sets () = let val S s1 = empty_set val S s2 = (#insert s1) 34 val S s3 = (#insert s2) 34 val S s4 = #insert s3 19 in if (#member s4) 42 then 99 else if (#member s4) 19 then 17 + (#size s3) () else 0 end
Again we are using no new features. #insert s1 is reading a record field, which in this case produces a function that we can then call with 34. If we were in Java, we might write s1.insert(34) to do something similar. The val bindings use pattern-matching to “strip off” the S constructors on values of type set.
There are many ways we could define empty_set; they will all use the technique of using a closure to “remember” what elements a set has. Here is one way:
val empty_set = let fun make_set xs = (* xs is a "private field" in result *)
| Cons(_,xs) => 1 + length xs
Using this library, here are two client functions. (The latter is not particularly efficient, but shows a simple use of length and filter.)
val doubleAll = map (fn x => x * 2) fun countNs (xs, n : int) = length (filter (fn x => x=n) xs)
Java 8 includes support for closures much like most other mainstream object-oriented languages now do (C#, Scala, Ruby, ...), but it is worth considering how we might write similar code in Java without this support, as has been necessary for almost two decades. While we do not have first-class functions, currying, or type inference, we do have generics (Java did not used to) and we can define interfaces with one method, which we can use like function types. Without further ado, here is a Java analogue of the code, followed by a brief discussion of features you may not have seen before and other ways we could have written the code:
interface Func { B m(A x); } interface Pred { boolean m(A x); } class List { T head; List tail; List(T x, List xs) { head = x; tail = xs; } static List map(Func f, List xs) { if(xs==null) return null; return new List(f.m(xs.head), map(f,xs.tail)); } static List filter(Pred f, List xs) { if(xs==null) return null; if(f.m(xs.head)) return new List(xs.head, filter(f,xs.tail)); return filter(f,xs.tail); } static int length(List xs) { int ans = 0; while(xs != null) { ++ans; xs = xs.tail; } return ans;
class ExampleClients { static List doubleAll(List xs) { return List.map((new Func() { public Integer m(Integer x) { return x * 2; } }), xs); } static int countNs(List xs, final int n) { return List.length(List.filter((new Pred() { public boolean m(Integer x) { return x==n; } }), xs)); } }
This code uses several interesting techniques and features:
There are many different ways we could have written the Java code. Of particular interest: