Using lazy evaluation to simulate a break

If you have done any programming with a procedural language, say C/C++/Java etc. you probably are familiar with the break statement. It’s basically a short-cut to break out of a loop.

The typical use case is, let’s say you are looking for something in a collection and you find it, you break out of the loop and notify the caller that you found it.

Let’s say we want to find the first prime number in a range of numbers. The code would look like:

Let’s ignore the implementation of the “isPrime” function for now and assume it’s part of the standard library. The point is, we break out of looking for results once a certain criteria is met. So, obviously the performance in the general case would be faster than say, looking through the entire range even if a match was found.

Now, how would you implement this in a functional language? We can get the same performance characteristics by using lazy collections, i.e. a collection whose value is realized only when it is absolutely needed.

Here’s how the clojure code would look:

Here range, filter and take all return lazy sequences. So we are getting the same performance guarantees as a break, i.e. take only invokes the computation on the lazy collection as many times as it needs to satisfy the count, in this case, 1.