Software has two ingredients: opinions and logic (=programming). The second ingredient is rare and is typically replaced by the first.
I blog about code correctness, maintainability, testability, and functional programming.
This blog does not represent views or opinions of my employer.

Sunday, July 21, 2013

Coding with Monads in Groovy, making Groovy more functional with Fpiglet

Monad is a quite simple concept yet is is perceived as a scary and complex thing that developers will never understand.  Fpiglet brings monadic computing to Groovy and the task should not be daunting at all.

History:  Monad concept came from Math, fortunately you do not need to understand much (or any) of Mathematics to understand and use monads.  In the nutshell, monads (in math, and in functional programming) are abstraction of 'container' concept.  Monad is simply a sophisticated term for a box.    If you know some Haskell you can read more about how math monads relate to monads used in programming: Haskell Understanding Monads (look at the end of that document).

What is it about:  It seems to me that functional programming is a simple concept that is made very confusing by all the attempts to express it using OO terms.  To any software engineer, Input-Output concept should be like bread and butter.  Functional programming is about transforming input to output.   The only trick is that these transformations are required to be pure (or safe) and are referred to as functions.
Pure/safe means that they do not change any state and do nothing else other than creating the output.

   data1 => function1 => data2 => function2 => data3 => ...

There is only one thing needed for that chain to work:  the result from function1 needs to match the input for function2...   This can be done by using bunch of tricks. One of them is the concept of curried functions (see my previous posts), another one is, yes, the monad.

In software we have a lot of boxes - we often put data into something that has additional context. Examples could be all the 'holder' classes which hold an object and some extra information.
One cool example is functional Either type which stores object or an error information why the object could not be created.  In this post, I will focus on one example that is very comprehensive and maybe one of the hardest to understand:  List as a Monad.

List as a Monad:
So putting a into a list [a] we are placing into a box. It even looks like a box ;)
This allows as to think about 'a' in a wider context of non-deterministic computations.  Typically when you perform an operation you just expect one result.  But if you define an operation like this
  Closure eitherAddOrSubtract1 = {a ->  [a-1, a+1]}

you are defining a function which says that there is more than one possible outcome.

So let us play some chess.  If position of my knight on the chess board is [0,0] (Groovy 2-element List) I can write the possible set of next positions as this:

(for simplicity I assume that chess board has no boundaries so I can move around in any direction).

We can define a knightMove function like so:
  FunList knightPositions= funlistIn << 
  //vector plus
  Closure vplus = f {a, b -> [a[0] + b[0], a[1] + b[1]]}
  def knightMove = {pos -> map(vplus(pos)) << possiblePositions}

(we are using Fpiglet here a bit, we are transforming Groovy list into a Functional List and use curried closures (see f in front of the closure) which can be applied with just one parameter even if they need 2. Please remember that << in Groovy is both closure composition as well as a way to pass argument to a closure)

It would be interesting to see where can I get in 3 moves.  So I would like to chain (compose) the calls to knightMove like so:
     knightMove << knightMove << knightMove << [0,0]

This will not work because knightMove output is a List of positions but input is a SINGLE position.
That seems more like artificial obstacle than anything else.  

This is what monad is about.  If you have a function (in a very pseudo code)
  fn: a  -> box a  //maps a to boxed a

then monad knows how to chain or compose it.  It does it by implementing a 'bind' function.
The following code in Fpiglet calculates a list of all possible knight positions after 3 moves

  Closure move3x= b(knightMove) << b(knightMove) << b(knightMove)
 FunList in3moves = move3x << [[0,0]] 

Bind function my look like magic, but it simply does what it says. It takes a function fn which accepts non-monadic type and returns a new function which accepts monadic type!  No rocket science (in very pseudo code):
  fn: a  -> box a  //or fn: T -> FunList<T>
  b(fn): box a  -> box a  //or b(fn):FunList<T-> FunList<T>

To do that 'binding' monad implementation needs to figure out how the 'boxing' works. For lists this ends up being concatenating all possible results.  Now, these functions will compose just fine. 

And you can chain as much as you want:
  def composeNtimes = f {n, Closure c -> 
       reduceR(COMPOSE) << take(n) << repeat(c)
  def inNmoves = f {n, initVal -> 
     composeNtimes(n,b(knightMove)) << [initVal]

  def in4Moves = inNmoves(4,[0,0])

Notice that the above example uses right fold.  The same can be accomplished using monadic fold (which is left fold).  I will add a test case to Fpilget source demonstrating monadic fold solution in a few days.

There is a more sophisticated idiomatic use of monads which I like to refer to as monadic comprehension.  You can do comprehensions with Fpiglet today, but most functional languages will give you some nice syntax sugar to make the code more readable.  
More info can be found on Fpiglet wiki pages, and I will write more at the time Fpiglet implements some syntax sugar for comprehensions.

-EDITED Aug 4, 2013- Fpiglet now implements simple monadic comprehension DSL!

You will find more examples of how to program with Monads in Fpiglet source code test folder.
I will be adding test code examples in the next few weeks.


No comments:

Post a Comment