For comprehension requires withFilter to destructure tuples

For comprehension requires withFilter to destructure tuples, though it looks natural to use this with any values.

import cats._
import cats.implicits._

val v = for { 
  (a, b) <- (1, 2).asRight[String] // Error value withFilter is not a member of Either[String, (Int, Int)]
} yield a + b

Below is a workaround using an intermediate value (though it is still possible to use ._1, ._2 values)

import cats._
import cats.implicits._

val v = for {
  result <- (1, 2).asRight[String]
  (a, b) = result
} yield a + b

This is within the scope of GitHub - oleg-py/better-monadic-for: Desugaring scala `for` without implicit `withFilter`s and it’s in Scala 3 by default under the -source:future flag

1 Like

Note that this already works in Scala 3 with the -source:future option:

$ scala3-repl -source:future
Welcome to Scala 3.1.0 (11.0.11, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
                                                                                       
scala> case class Foo(x: (Int, Int)) { def map(f: ((Int,Int)) => (Int,Int)): Foo = Foo(f(x)) }
// defined case class Foo
                                                                                       
scala> for (a, b) <- Foo((1, 2)) yield (b, a)
val res1: Foo = Foo((2,1))
1 Like