FPOO Chapter 6: Inheritance

Note: This article is part of a series working through the exercises in Brian Marick's "Functional Programming for the Object-Oriented Programmer", in Elixir instead of Clojure. The full notes and source code are on GitHub.

Inheritance means knowing who your parent is.

Now to define the anything class, referenced above by the keyword :__superclass_symbol__.

And now the real magic: method lookup!

The top-level method lookup function:

Notice that I’ve had to reverse the order of the arguments to Dict.merge/2. This is because reduce passes arguments in the order next_item, accumulator, but I want methods from each successive class in the lineage to override methods in earlier, less-specialized classes.

A helper to get the instance methods defined for a class:

Another helper to get the parent class symbol:

…and a function to get the ancestry chain of a given class:

Now to update apply_message_to to use this new code:

Before I go any further, I feel a compulsion to try and golf down the method_cache function.

Ah, lovely.

Exercise 1: factorial

Just for fun, I’ll do this one in a single definition instead of multiple pattern-matching definitions.

Exercise 2: factorial, accumulator style

Exercises 3-6: implementing reduce

I’m going to skip these for now.


One of the things I like about this section, and this book, is that Marick explicitly identifies functional patterns, such as the two styles of recursive method definition. He even shows “ideal forms” of the two patterns, with placeholders for the parts that change.

I’ve definitely seen these styles in use, but hadn’t seen them clearly elucidated as patterns before. If nothing else, this book should put the rest the notion, occasionally advanced, that patterns are somehow not applicable to functional programming. Every community develops patterns; being able to identify them and point out which parts are consistent and which parts change with the application is one of the marks of a good software writer.