Lazy evaluation with a predicate

haskell, lazy-evaluation

Solution

Here is an example of what you want

length $ take 10 $ filter even [1..]

[1..] is infinite, so if this weren't lazy, the program would hang.

You are pipeing [1..] through a filter `even`, then capping the number at 10.... Then you do something with that list. Instead of `length`, you could check if it reached the threshhold by using `(>= 10) $ length`).

Problem

I'm trying to write a function in Haskell that counts the elements in a list satisfying a predicate and returns `True` if the number exceeds some threshold. I have an implementation that looks like this: ``` hitsThreshold :: Int -> (a -> Bool) -> [a] -> Bool hitsThreshold threshold test strs = (length $ filter test strs) >= threshold ``` The problem is, I want this to evaluate lazily so that it will terminate as soon as the length reaches the threshold. For example, I should be able to pass in an infinite list and it should terminate in finite time (assuming the threshold is reached eventually). Is there a simple way to do this?

Original source