chapter five

5 Higher-kinded composition

 

This chapter covers

  • The advantages of programming with immutable, composable objects
  • How to map and flatMap over arrays and any object
  • The basics of functors and monads
  • Understanding the relationship between map and compose
  • Writing a Validation Algebraic Data Type (ADT)
  • Composing validated data flows via the HasValidation mixin

“The purpose of abstraction is not to be vague, but to create a new semantic level in which one can be absolutely precise”

Edgar Dijkstra

In the previous chapter you learned how function composition leads to very fluent, compact, and declarative code using compose to chain your function’s inputs and outputs as data passes through them. Composition has a lot of benefits because it uses JavaScript’s strongest feature: higher-order functions. With functions you can achieve low-level composition. With the help of some simple APIs, you can achieve a higher-kinded composition.

Take a moment to reflect about some of the problems we tackled in chapter four. What would happen if the data that one function receives along the chain were invalid, null, or undefined? Syntactically speaking, when using compose you can’t insert imperative conditional validation blocks in between logic functions. Your best bet would be to move validation logic into its own function, as such:

5.1 Closing over data types

5.1.1 Using containers for encapsulation and immutability

5.1.2 Contextual composition

5.1.3 JavaScript data types

5.2 New Array APIs: {flat, flatMap}

5.2.1 Array.prototype.flat

5.2.2 Array.prototype.flatMap

5.3 The *map/compose correspondence

5.4 Universal protocols

5.4.1 Functors

5.4.2 Monads

5.5 Kinds of Algebraic Data Types

5.5.1 Records

5.5.2 Choices

5.6 Implementing the Validation ADT

5.6.1 Modeling success and failure

5.6.2 Basic usage

5.6.3 Higher-kinded composition with Validation

5.6.4 Point-free coding with ADTs

5.6.5 Validating complex data structures

5.6.6 Third-party integration

5.7 Future ADT-inspired JavaScript proposals

5.7.1 Maybe and optional chaining

5.7.2 Try and throw expressions

5.7.3 Pattern matching

5.8 Summary