Tuesday 2 January 2018

Writer Monad from Scala Cats

Once upon a time there was some stinky side affecting code with println all over the place.


How horrible! No, Cinderella, you definitely can't meet the prince of MonadLand looking like that!
Fortunately her Functional Fairy Godmother is on hand.



 'Ah ha' she cries! From each function you need to return both the int (which is the existing return type) and some Strings to represent the logs!

'Easy peasy' she says and with a swish of her magic wand she transforms Cinderella.

Well I guess this is ok, but look how much more effort Cinderella has to go to to compose f and g! That's not very elegant at all!

'Please, Fairy Godmother', Cinderella begs, 'Isn't there anything more you can do?'

Now it's a little-known Disney secret that Cinderella's Functional Fairy Godmother is actually an enormous fan of Cats and has a clever Writer monad trick up her sleeve.

Output:

WriterT((Vector(Generating random int, Applying complex mathematical formula),84))
WriterT((Vector(Generating random int, Applying complex mathematical formula),84))

'Oh thank you Functional Fairy Godmother', cries Cinderella, delighted.

FFG winks and whispers, 'I just love a good for comprehension! There are actually a lot of different ways of creating a writer!', and she slips some example code into Cinderella's pocket for later bedtime reading, in case things with the prince don't go to plan:

Cinderella was so intrigued by these examples that she stayed up all night reading Dave Gurnell and Noel Walsh's book Scala with Cats and skipped the ball entirely.


And she lived happily ever after. 

No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...