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
No, this is not possible! The reason is because _before_ we ever call our function, `f`, we evaluate its argument, which in the case of `foldRight` means traversing the list all the way to the end. We need _non-strict_ evaluation to support early termination---we discuss this in chapter 5.
However, providing a second higher-order function that checks for an early termination + a return value for that case makes early termination possible. A crude implementation might look like this:
deffoldRight[A, B](as: List[A], z: B)(f: (A, B) =>B)(abort: (A=> (Boolean), B)):B=// Utility functions
as match {
caseNil=> z
caseCons(x, xs) =>if (abort._1(x)) abort._2 else f(x, foldRight(xs, z)(f)(abort))
}
defproduct2(ns: List[Double]) =
foldRight(ns, 1.0)(_ * _)((_ ==0.0, 0.0)) // `_ * _` is more concise notation for `(x,y) => x * y`; see sidebar
The question is if the
product2
method implemented usingfoldRight
can terminate early with the result0.0
if it encounters0.0
in the list.The method is defined here:
fpinscala/exercises/src/main/scala/fpinscala/datastructures/List.scala
Line 49 in 71a7931
The answer given is no, it cannot terminate early:
fpinscala/answerkey/datastructures/07.answer.scala
Line 2 in 71a7931
However, providing a second higher-order function that checks for an early termination + a return value for that case makes early termination possible. A crude implementation might look like this:
To wit:
The text was updated successfully, but these errors were encountered: