Posts

Showing posts from March, 2012

Memorizers in Scala

Today I will talk about anonymous functions and memorizers. Here is a simple, self-sufficient anonymous function (I think it is the simplest possible): val fun = (a:Int) => a + 1 What's wrong with it? Nothing, except for the fact, that it would recompute the value every time it is called. In case of adding 1 to argument, it is not a problem, but what if we would be doing something expensive? Wouldn't it be cool to be able to do something like following? val fun = mem( (a:Int) => a + 1 ) And Scala permits us to do exactly this: def mem[A,B](f:A=>B) = new Function[A,B] { import scala.collection.mutable.Map; private var cache:Map[A,B] = Map() def apply(v:A):B = cache getOrElseUpdate(v,f(v)) } val fun = mem( (a:Int) => a + 1 ) Now, we have a function, that stores all the computed results into a Map, and does not recompute them. There are several minor problems with this approach - for example, it is not thread-safe, and sharing this function between thre