Lazy evaluation in Python

The object returned by range() (or xrange() in Python2.x) is known as a lazy iterable. Instead of storing the entire range, [0,1,2,..,9], in memory, the generator stores a definition for (i=0; i<10; i+=1) and computes the next value only when needed (AKA lazy-evaluation). Essentially, a generator allows you to return a list like structure, but … Read more

Python’s xrange alternative for R OR how to loop over large dataset lazilly?

One (arguably more “proper”) way to approach this would be to write your own iterator for iterators that @BenBolker suggested (pdf on writing extensions is here). Lacking something more formal, here is a poor-man’s iterator, similar to expand.grid but manually-advancing. (Note: this will suffice given that the computation on each iteration is “more expensive” than … Read more

Java streams lazy vs fusion vs short-circuiting

As for fusion. Let’s imagine here’s a map operation: .map(x -> x.squash()) It’s stateless and it just transforms any input according to the specified algorithm (in our case squashes them). Now the filter operation: .filter(x -> x.getColor() != YELLOW) It’s also stateless and it just removes some elements (in our case yellow ones). Now let’s … Read more

Directory.EnumerateFiles => UnauthorizedAccessException

I Couldn’t get the above to work, but here is my implementation, i’ve tested it on c:\users on a “Win7” box, because if has all these “nasty” dirs: SafeWalk.EnumerateFiles(@”C:\users”, “*.jpg”, SearchOption.AllDirectories).Take(10) Class: public static class SafeWalk { public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOpt) { try { var dirFiles = Enumerable.Empty<string>(); if(searchOpt == … Read more

Lazy evaluation in C++

I’m wondering if it is possible to implement lazy evaluation in C++ in a reasonable manner. If yes, how would you do it? Yes, this is possible and quite often done, e.g. for matrix calculations. The main mechanism to facilitate this is operator overloading. Consider the case of matrix addition. The signature of the function … Read more