Posted By

narkisr on 08/11/09


Tagged

closure groovy functional memoization


Versions (?)

Closure memoization in Groovy


 / Published in: Groovy
 

URL: http://cromwellian.blogspot.com/2006/07/infinite-streams-in-groovy-in-my-last.html

This example shows how its possible to cache (memoization) a Closure value, note that this works only for a single value per each delay method call (the Closure creates a closed scope in which its "state" is kept).

  1. public delay(Closure c)
  2. {
  3. boolean evaled=false
  4. def val=null
  5. return {Object[] args ->
  6. if(!evaled) { evaled=true; val=c(args[0]); return val }
  7. else return val;
  8. }
  9. }
  10.  
  11. c = {v ->
  12. println 'hello'
  13. 1+v
  14.  
  15. }
  16.  
  17. d = delay(c)
  18. println d.call(1)// hello will not be printed
  19. println d.call(2)// we will not eval, the result will be 2 & not 3!

Report this snippet  

You need to login to post a comment.