FPOO Chapters 2 & 3: Basic Objects in Elixir

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.

I feel like I should start with a disclaimer: this post is not advocating building an OO system on top of an FP language. And anyway, the Elixir/Erlang “process” model is arguably a very OO system right out of the box. But this series is about working through the FPOO book, and the exercise that’s up next is to implement a basic OO system on top of an FP language, so that’s what I’m going to do.

First version, without knowledge of class:

(Note: when I wrote this I either didn’t know, or had forgotten, that subscript/square-bracket access was available in Elixir. So you’ll see a lot of get(point, :x) when I probably could have written point[:x].)

Second version, with knowledge of class and shift method:

Exercise 1: Implement add

I think I’ll switch over to doctests instead of separate unit tests.

Exercise 2: A “new” operator

If I did this exactly like the Clojure version I’d have to call it like this:

Blerg. I’ll make a macro instead.

OK, that was kinda cool. Of course, if I were willing to put up with passing the classname as a symbol rather than as a bareword, I wouldn’t need a macro.

Note the use of delegate_locals_to: __MODULE__ to enable the eval_quoted to find methods in the current module. I’m still getting the hang of eval-ing in Elixir; there may be a better way to do this.

The next three exercises involve comparing triangles and I just can’t get excited about that, so I’m gonna stop here.