You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
5. Compute `f False 3` $\to$ `True`. But now we must recurse: `foldl (...) True [4,5,6,...]`.
727
-
6. Compute `f True 4` $\to$ `True` (since `4 /= 3`, it returns the accumulator `True`). But we recurse again: `foldl (...) True [5,6,7,...]`.
728
-
7. This continues forever. Even though we found `3`, we never stop.
723
+
- Start: `acc = False`, list `[1,2,3,4,...]`.
724
+
- Compute `f False 1`, which evaluates to`if 1 == 3 then True else False`, resulting in `False`. Recurse: `foldl (...) False [2,3,4,...]`.
725
+
- Compute `f False 2`, which results in `False`. Recurse: `foldl (...) False [3,4,5,...]`.
726
+
- Compute `f False 3`, which results in `True`. But now we must recurse: `foldl (...) True [4,5,6,...]`.
727
+
- Compute `f True 4`, which results in `True` (since `4 == 3` is `False`, it returns the accumulator `True`). But we recurse again: `foldl (...) True [5,6,7,...]`.
728
+
- This continues forever. Even though we found `3`, we never stop.
729
729
730
-
<br>The `foldr` function can terminate on infinite lists if the function `f` is lazy in its right argument (i.e., `f` can short-circuit by ignoring the recursive result).
730
+
The `foldr` function can terminate on infinite lists if the function `f` is lazy in its right argument (i.e., `f` can short-circuit by ignoring the recursive result).
731
731
The `foldl` function always processes the list from left to right and cannot short-circuit in the same way, so it fails on infinite lists.
732
732
This is why `foldr` is often more suitable for working with infinite lists. Just remember: **the function `f` must be lazy in its right argument for `foldr` to terminate early**.
0 commit comments