Loading...
intermediate
Problem 08 • Step 03
Naming the Selectors
The 0 and 1 in call(call(call("pair", 3), 4), 0) are magic numbers. Someone reading this code has to remember that 0 means first and 1 means second.
Define two functions that hide the selectors behind meaningful names:
evaluate(call("head", call(call("pair", 3), 4))) // 3
evaluate(call("tail", call(call("pair", 3), 4))) // 4
Each function takes a pair and calls it with the right selector. One line each.
Look at what happened across these three steps:
- A function can remember a value (closure)
- A function can remember two values and let the caller choose (selector)
- Named accessors hide the selection mechanism (abstraction)
The pair is the function. The data lives inside a closure. Access is function application. head and tail are just a naming convenience, but that convenience turns a closure trick into something that behaves like a real data structure.