Any trick to fold and map Applicative at once

108 Views Asked by At

For instance, I have an easy code snippet:

import cats.instances.option._
import cats.syntax.option._
import cats.syntax.apply._

val a = 1.some
val b = 2.some

(a, b).mapN(_ + _)

I wish to fold this to result or 0.
Are there any alternatives to .getOrElse(0)?

Maybe a kind of:

(a, b).foldN(0)(_ + _) // foldN actually does not exists 
1

There are 1 best solutions below

0
On BEST ANSWER

Do you have to use a tuple there? If you used NonEmptyList or NonEmptyChain you can simply do

NonEmptyList.of(1.some, 2.some).reduce // Some(3)

or

NonEmptyList.of(1.some, 2.some).reduceMap(_.getOrElse(0)) // 0

or any other combination utilizes of NonEmpty* or Traverse.

You cannot run away from getOrElse entirely. At some point you have to provide some Option[Int] => Int mapping, either in foldMap, reduceMap or after folding/reduceing. You might replace that with fold on Option or something else but no Applicative utility would do this for you as exiting the context F is not a part of an Applicative interface (more like a Comonad).