Early-stops in folds in Scala with Cats

Image for post
Image for post

Catamorphism (e.g. ‘fold’) is a great concept in purely functional programming. It is a common case when you want to “fold” the whole structure into another with the initial value.

However, sometimes it might be confusing even in simple cases.

Let’s say you want to sum your list of int values (which, of course, has been already implemented as sum for you in the Scala Collection Library).

This should be easy:

Now let’s say you’d like to stop counting and computation if your sum is more than some specified max value:

So, basically we’re looking for some kind of `foldWhile`, but unfortunately there isn’t a ready to use function in the Scala library.

There are solutions for this:

  • 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

An additional feature here is if you really need it, you can detect if it was an early stop or not (Either.Left for an early-stop in our example).

This little trick helps to be more productive, enjoy.

Software Developer & Architect

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