In memoization, the results of a function are memoized— recorded in a Map indexed by the function’s argument(s). This saves computation required to execute the original function as well as reducing memory which which might be used up by keeping multiple copies of the result. However, it only makes sense when the arguments and the result type are immutable.

     // this only handles functions with a single argument.
     def  memo[X,R](f: X=>R)={
	 // a WeakHashMap will release cache members if memory tightens
         val cache=new scala.collection.jcl.WeakHashMap[X,R];
	 {(x:X) => cache.getOrElseUpdate(x,f(x));}
     }
 
      // function to be memoized      
      def f(i:Int)={println("called f with "+i); i*2+1 }
      
      // this needs to be a function; if it were a method (with def) 
      // it would point to0 rather than evaluate the memo call.
      val g=memo(f);
 
      for (j <- 1 to 3){
	println(g(j));
      }
      for (j <- 1 to 3){
        // f will no bet called by these invocations of g
	println(g(j));
      }

Both Scalax and Scalaz support memoization.

 
patterns/memoization.txt · Last modified: 2010/02/11 09:10
 
Recent changes RSS feed Valid XHTML 1.0 Driven by DokuWiki