Your Location is: Home > Scala

Shorthand for map traverse reduce

From: Papua-Neuguinea View: 4704 Some Name 

Question

I'm looking for a short way to traverse and reduce at the same time. Here is the solution I came up with:

import cats.{Applicative, Monad}
import cats.instances.list._
import cats.syntax.functor._
import cats.syntax.flatMap._
import cats.syntax.traverse._

object Test extends App {
  def intFM[F[_], M[_]](i: Int): F[M[Int]] = ???

  def traverseReduce[F[_]: Applicative, M[_]: Monad](lst: List[Int]) =
    lst.traverse(intFM[F, M]).map(_.reduce(_ >> _))
}

As can be seen I did 3 operations: traverse, map and reduce, but I expected that it was possible to do the reduction while traversing. Is there some shorthand?

Best answer

You can try without traversing

def traverseReduce[F[_]: Applicative, M[_]: Monad](lst: List[Int]): F[M[Int]] =
  lst.map(intFM[F, M]).reduce((_, _).mapN(_ >> _))