Closures

intermediate

You just turned eight operator rules into one by treating operators as curried functions. Let’s push that idea further.


Functions that Make Functions

A curried function returns another function. What if you used that pattern on purpose. A function whose entire job is to produce customized functions?

Imagine a make-adder function. You call it with 3, and it gives you back a function that adds 3 to anything. Call it with 5, and you get a function that adds 5. One definition, infinite specialized functions.

evaluate(["add3", "=", ["make-adder", 3]]);
evaluate(["add5", "=", ["make-adder", 5]]);
evaluate(["add3", 10]); // should be 13
evaluate(["add5", 10]); // should be 15

This is a powerful pattern. In most languages it just works.


What You’ll Do

  1. First, you’ll define make-adder and try to use it, and discover that our evaluator has a bug
  2. Then, you’ll fix the bug by giving each function call its own scope

Steps