Early-stops in folds in Scala with Cats

List(1,2,3,4,5).foldLeft(0)( _ + _ )
val max = 5
List(1,2,3,4,5).foldLeft(0) { case (total, x) =>
val ux = total + x if ( ux < max )
ux
else
??? // Now what?
// We can't continue and have to stop
// 2 reasons to stop:
// - avoid wasting of computational resources
// (imagine if you have very long stream of values)
// - possible incorrect results
// without additional conditional params
}
  • Own tail-recursive function instead fold
  • Use gruesome return (and ready to be hated by your teammate).
  • Use throw (not much better… or even worse?)
  • Use while and var (an imperative style)
  • And finally, my favourite one, use foldM from Cats and Either from Scala
import cats.implicits._val computed: Int =
List( 1, 2, 3, 4, 5 )
.foldM( 0 ) {
case ( total, x ) =>
val ux = total + x
if (ux < max)
ux.asRight // implicitly creates Either.Right here
else
total.asLeft // implicitly creates Either.Left here
}
.merge // we're merging Either[Int,Int] to Int

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store