14 Functional tools for nested data

 
Image

In this chapter

  • Build higher-order functions that operate on values stored in hash maps.
  • Learn to easily operate on deeply nested data with higher-order functions.
  • Understand recursion and how to do it safely.
  • Understand when to apply abstraction barriers to deep, nested entities.

We’ve learned several useful functional tools that operate over arrays. In this chapter, we’re going to derive and use functional tools that operate on objects as hash maps. These tools allow you to operate on deeply nested maps, which we often find as we build more complex data structures together. Without the tools, operating on nested data in an immutable way is very awkward. But with the tools, we are free to nest as deeply as we like, which gives us the freedom to structure our data however we see fit. These higher-order functions are very common in functional languages.

Higher-order functions for values in objects

Image

CMO: Well, we’ve been using your higher-order functions and they’ve really helped clean up our code.

Jenna: Great!

CMO: Yes! Truly great. We’ve actually done a lot of cleanup using the refactorings that you showed us a couple of chapters ago. But now we’re doing all of these operations that must be higher-order functions, and we just can’t figure out how.

Jenna: Ah, okay. Can you tell me more?

Making the field name explicit

Deriving update()

Using update() to modify values

Refactoring: Replace get, modify, set with update()

Functional tool: update()

Visualizing values in objects

Visualizing nested updates

Applying update() to nested data

Deriving updateOption()

Deriving update2()

Visualizing update2() on nested objects

Writing incrementSizeByName() four ways

Deriving update3()

Deriving nestedUpdate()

The anatomy of safe recursion