Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell filter function laziness

Tags:

haskell

Given:

take 5 (filter p xs)

say if filter p xs would return 1K match, would Haskell only filter out 5 matches and without producing a large intermediate result?

like image 458
Sawyer Avatar asked Nov 25 '25 15:11

Sawyer


1 Answers

It will scan xs only as much as needed to produce 5 matches, evaluating p only on this prefix of xs.

To be more precise, it can actually perform less computation, depending on how the result is used. For instance,

main = do
   let p x = (x==3) || (x>=1000000)
       list1 = [0..1000000000]
       list2 = take 5 (filter p list1)
   print (head list2)

will only scan list1 until 3 is found, and no more, despite take asking for five elements. This is because head is demanding only the first of these five, so laziness causes to evaluate just that.

like image 122
chi Avatar answered Nov 27 '25 07:11

chi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!