Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy evaluation with a predicate

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?

like image 911
Michael Dickens Avatar asked Dec 26 '22 16:12

Michael Dickens


1 Answers

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).

like image 189
jamshidh Avatar answered Jan 08 '23 17:01

jamshidh