Chain of responsibility in Scala using partial functions II: currified functions

Manuel Rodríguez
2 min readJun 21, 2019

--

In the previous post we saw an example of implementing the Chain of Responsibility pattern. But what happens if the functions to execute are a bit more complex? In this case I want a function with two parameters (NumberRules) which will apply Chain of Responsibility over the first one. How can that be implemented on a functional way?

Here I am presenting an implementation based on currification. I like because, although conceptually is slightly more complex, the resulting code is extremely clean an compact. And also, “currification” is probably the best name for any computational process.

As usual, let’s dive into the code! I won’t go into the details when the explanation can be seen in the previous post, so feel free to navigate there and come here when everything is fully understood.

2.

This time our partial function will not return a value but another function: one that receives a String and returns another one

4.

Tricky part here is the second parameter. That parameter represents a high order function: a function that, when receiving an Int, will return a function that receives a String and returns another one. This is a bit difficult to explain but will result obvious later.

8 and 9.

These are our partial functions. If they receive an integer as a parameter, they return a function that add some stuff to a String and returns another one. And if they receive both an Int and a String, they do all the job and return a String.

15.

Note that NumberRulesFn is returning a high order function here, with type String=>String

19.

Here comes the magic. What we want is a function with 2 parameters (first Int, second String) with CoR on the first one. We use NumberRulesFn with an applyOrElse, and as the partial functions are currified, my result is of type String=>String. I execute it with (s) and that’s it!

--

--

Manuel Rodríguez

Developer at New Relic. This is where I keep the cool stuff that I learn in my free time