Advertisement
Guest User

Lazy values in D

a guest
May 24th, 2014
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct Lazy(T) {
  2.   bool forced = false;
  3.  
  4.   // Ideally thunk and value would be part of a union
  5.   // but I don't know if that would work with D's GC.
  6.   T function() thunk;
  7.  
  8.   T value;
  9.  
  10.   this(T t) { thunk = T function() { return t; }; }
  11.  
  12.   @property T force() {
  13.     if (!forced) {
  14.       value = thunk();
  15.  
  16.       // thunk should now be garbage
  17.       thunk = null;
  18.     }
  19.  
  20.     return value;
  21.   }
  22.  
  23.   alias force this;
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement