Recently, I bought the fantastic book Functional Programming in Scala (P.Chiusano, Rúnar Bjarnason) and yesterday I realized that I started following a precise path when I have to solve an exercise.

I have to implement the classical function flatMap for a type State as per this stub:

So I start playing with types: rather than beginning to call methods and figuring out data flows, I just declare some variables and type annotations to match the returning type of the function.

In this case, I name the returning value after its type:

This stub, which is just a bit more than the original one, compiles. And it can be also called at runtime, it just won’t behave as expected, but the compiler is telling me that the direction is good.

I see it as my first MVP: it compiles successfully, but there is still missing logic.

From the flatMap annotation, I see that I have a function f producing the result I’m looking for: it might work.

Still compiling. The reason why I can move the function around and apply the substitution model is because I’m working with pure functions.

But now I need an A, where can I find it? Looking at the definition of my class, I see that I actually have a function in my scope which returns a tuple containing an A: it is the function run. But it needs to be called with an S. Where can I get it from?

I looked a bit around it, when I realized something cool: State[S,B] can be written in terms of its constructor, and it gives access to a parameter of type S:

It compiles! Now I have an S and a function of S => (A, S) to get the A needed to eventually produce a B.

Let’s put it all together again, with a modification: this time the result can’t be a State[S,B] otherwise the final result would be State[State[S,B]]. It must be a simple tuple (S, B).

I have the green light from the compiler, so I assume I’m doing it right!

Let’s complete it, calling the function f.

It compiles, and works as expected! It’s working, finally.

Now, let’s get rid of some redundant type annotations and intermediate variables, taking advantage of Scala’s type inference and expressiveness.

Note that although this answer works and is functional, the correct answer from the book is slightly simpler. I prefer to show you mine since the point here is not the solution itself but the mental process which drove me here.

I found this flow really helpful and effective: I prefer it to the fussy testing I’m used to in the frontend world, where I need to write a test which asserts that a string is an actual string.

Nonetheless, I’m not saying this is the definitive technique and neither that you should switch to it right now. It for sure require a strongly, statically typed language like Scala.

It works for me, and I enjoy writing about it.