When I find something interesting and new, I post it here - that's mostly programming, of course, not everything.

Monday, March 29, 2010

Hidden Monads in Scala

Actually, not monads, just functorial stuff. But programmers seems to be unaware of the fact that a monad is a special kind of functor, so...

In Scala, one can define a functor something like this:

  trait Functor[X] { 
def map[Y](f: X => Y): Functor[Y]
}


All we need here is map. Lists have map, Options have map... The natural use of a map is to apply it to a function. Like this:


def loop[X,Y](f: Functor[X], a: X=>Y) = f.map(a)


In Scala, loops can work as maps. And if you are a Haskell programmer, you'll immediately recognize your monadic notation:

  
def loop[X,Y](f: Functor[X], a: X=>Y) = for (x <- f) yield a(x)



These two are exactly the same.

Praise Scala!

Update: see recent blog entry on monads by Luc Duponchel for a lot more details.

No comments:

Followers

Subscribe To My Podcast

whos.amung.us