Some Fun - Sickness of using Java Builder in Functional Programming — Solved
This is written simply for fun. And you are reading it to apply the knowledge in your application code — for fun without hurting the readers of your code.
Please don’t read this if you hate Functional Programming and being declarative.
Please don’t read this if you think Monad is pain in the ass — Lets be just friends.
Problem — Well, not exactly, but anyways!
Assume you have 2 optional parameters:
Maybe(firstName), Maybe(lastName) You want to instantiate (or build an instance of)
Name class which is possibly written in Java with these parameters, if they exist (ie; Maybe.Just, or Option.Some).
Ok! Let us try writing it.
Think of multiple classes similar to
Name with multiple (a list of) optional parameters. Now, this is our problem definition. A quick solution would be abstracting out the above function (say f) and fold the list of optional parameters (using f), but that is in fact, discarding the possibility of using a better mechanism provided by Functional Programming paradigm. Below given is one of the solutions. While this may not be the only solution, it is still a cleaner way of solving this problem.
A Solution - State Monad
I have intentionally avoided the use of
State.modify function in scalaz, since it is less expressive at this stage.
If you don’t know State..
You can see some of my code scribblings on State data-type (without scalaz) in the following links. You may read them in its order. The comments in code may give you some idea on what is state data type. That will make you feel comfortable with some notes in scalaz tutorial (Google).