[SOLVED] Short cut for partitionMap

In my codebase I see my self doing something like that:

val (left, right) =
  List(Right(1), Right(2), Left("three"), Right(4)).partitionMap {
    case Right(value) => Right(value)
    case Left(value)  => Left(value)
  }

The two lines,

case Right(value) => Right(value)

and

case Left(value)  => Left(value)

are bugging me. It looks to me as I would just return what I get, without doing anything with it.

Is there a shortcut for this?

Looks like you could use the identity function or x => x.

List(Right(1), Right(2), Left("three"), Right(4)).partitionMap(identity)
// or
List(Right(1), Right(2), Left("three"), Right(4)).partitionMap(x => x)
1 Like

I would also add that probably you may have done the partition map before.

1 Like

Thank you for this thoughtful addition, but my example is just a minimal, reproducible example to demonstrate what I am talking about :slight_smile:

FWIW, what if we didn’t have partitionM but just partition? I had a go:

val list = List(Left("bang"),Right(3),Left("boom"),Right(5))

val expected = (List("bang","boom"), List(3, 5))

assert( expected == (list.partition(_.isLeft) 
                       match { case (ls, rs) => 
                         (ls.map(_.merge), 
                          rs.map(_.merge)) 
                       }))

// hack
assert( expected == list.map(_.merge).partition{ 
                      case s:String => true; 
                      case _ => false })


// let's use cats
import cats.implicits._

assert( expected == list.partition(_.isLeft)
                        .bimap(_.traverse(_.swap).merge,
                               _.sequence.merge)) 

assert( expected == list.partition(_.isLeft)
                        .bimap(_.map(_.merge),
                               _.sequence.merge))

assert( expected == list.partition(_.isLeft)
                        .bimap(_.map(_.merge),
                               _.map(_.merge)))

assert( expected == list.partition(_.isLeft)
                        .binested
                        .bimap(_.merge,_.merge)
                        .value)