More on Functional Programming

Keywords

ver. 1.0.0

How functions (and closures) provide abstraction, control and even objects

This unit explores higher-order functions, function composition patterns (map, reduce, filter), partial application, closures and how closures can implement control structures and message-passing objects; it contrasts closure-built objects with Clojure’s preferred data-oriented style.

You will deepen your fluency with functions as first-class values and learn how they serve as the primary tools for abstraction and structure. Starting from the idea of higher-order functions — functions that take or return other functions — you will see how common collection operations arise by abstracting what varies: applying an operation across every element (map), combining elements into a single result (reduce), and selecting elements that meet a condition (filter).

You will practice fixing some arguments of multi-argument functions to create more specific functions, first by hand with closures and then with a utility that does the same work. That exercise shows how partial application customises behavior without rewriting code.

Closures are defined and explained via free variables: a function together with the bindings it captures from its defining environment. You will use closures both to delay or control evaluation — wrapping computations so they run only when invoked — and to implement reusable control structures (for example, a try/catch style wrapper that accepts risky work as a postponed function).

Building on captured state, you’ll create message-passing entities: functions that hold private data and dispatch behaviour based on messages, thereby forming basic objects. From this you can assemble a small object system entirely from closures, and you will consider what that reveals about alternatives. In particular, you will contrast closure-based objects with Clojure’s idiomatic approach of plain immutable data plus separate functions: data structures are transparent, printable and comparable, while closures are opaque but can encapsulate private state and behaviour.

By the end you will be able to recognise and write higher-order functions, collect and reduce collections, filter elements, create partially applied functions, identify free variables and explain closures, write closure-producing functions that capture state, use closures to delay computation and create control structures, and build simple message-passing objects — and you will be able to weigh when closure-based objects are appropriate versus preferring data-oriented designs.

Materials

Source document

  • Clojure in Action (2nd Edition), A. Rathore and F. Avila, Manning, Dec. 2015 — Link — Page 209-239