Abort early in a fold
Posted
by
Heptic
on Stack Overflow
See other posts from Stack Overflow
or by Heptic
Published on 2012-10-15T09:24:59Z
Indexed on
2012/10/15
9:37 UTC
Read the original article
Hit count: 148
scala
|functional-programming
What's the best way to terminate a fold early? As a simplified example, imagine I want to sum up the numbers in an Iterable, but if I encounter something I'm not expecting (say an odd number) I might want to terminate. This is a first approximation
def sumEvenNumbers(nums: Iterable[Int]): Option[Int] = {
nums.foldLeft (Some(0): Option[Int]) {
case (None, _) => None
case (Some(s), n) if n % 2 == 0 => Some(s + n)
case (Some(_), _) => None
}
}
However, this solution is pretty ugly (as in, if I did a .foreach and a return -- it'd be much cleaner and clearer) and worst of all, it traverses the entire iterable even if it encounters a non-even number.
So what would be the best way to write a fold like this, that terminates early? Should I just go and write this recursively, or is there a more accepted way?
© Stack Overflow or respective owner