Sunday, December 30, 2012

First Scala Monad example

So as promised here is my first scala monad example

trait Function {
  def name: String
}

case class ShellFunction(name: String) extends Function
case class ScalaFunction(name: String) extends Function

val l: List[Option[Function]] = List(None, Some(ShellFunction("build")), None)

val resultUsingForConstruct = for (
  i <- l;
  j <- i
) yield (Some(ScalaFunction(j.name)))

val resultUsingFlatMap = l flatMap {
  i: Option[Function] => i map {
    j: Function => Some(ScalaFunction(j.name))
  }
}

println("Result using for construct: " + resultUsingForConstruct)
println("Result using flatmap construct: " + resultUsingFlatMap)
Output: List(Some(ScalaFunction(build)))

As you can see flatMap removes those None's from our computation.

Thursday, December 27, 2012

Monads in Scala world


I have been wanting to blog for some time now, so just updated my blogging profile :) I will be sharing resources and articles which will help us better understand intricacies of the programming world.

The word Monad - a word coming from category theory and Haskell FP world.

I am still learning from it, and to the best of my understanding (at this hour) I have come to believe that it a pattern of programming to avoid those nasty null checks.

Scala provides that in the language feature in the form of List and Option monads. Although my understanding is still fuzzy, I want to share a few resources that have helped me in understanding them.

http://debasishg.blogspot.in/2008/03/maybe-scala.html
http://www.codecommit.com/blog/ruby/monads-are-not-metaphors
http://debasishg.blogspot.in/2008/03/maybe-scala.html

I would request you to go through those links in that order. Will update the blog adding more resources and examples as I go along.

Hopefully one day I will be able to post a detailed article about monads :)