将选项元组转换为具有Scalaz或Shapeless的元组选项



具有

(Some(1), Some(2))

我希望得到

Some((1, 2))

并且具有

(Some(1), None)

我希望得到

None

我知道你在问Scalaz,但值得指出的是,标准方法并不冗长:

val x = (Some(1), Some(2))
for (a <- x._1; b <-x._2) yield (a,b)

在一般情况下(例如任意arity元组),Shapeless最擅长这类事情。

您可以使用Scalaz 7为元组提供Bitraverse实例的事实,然后照常排序(但使用bisequence而不是sequence):

scala> import scalaz._, std.option._, std.tuple._, syntax.bitraverse._
import scalaz._
import std.option._
import std.tuple._
import syntax.bitraverse._
scala> val p: (Option[Int], Option[String]) = (Some(1), Some("a"))
p: (Option[Int], Option[String]) = (Some(1),Some(a))
scala> p.bisequence[Option, Int, String]
res0: Option[(Int, String)] = Some((1,a))

不幸的是,Scalaz7当前需要在此处进行类型注释。


Yo Eight在一条评论中指出,类型注释在这里仍然是强制性的。我不确定他或她的推理是什么,但事实上,编写自己的包装器非常容易,它将使用bisequence方法提供任何适当类型的元组,并且不需要类型注释:

import scalaz._, std.option._, std.tuple._    
class BisequenceWrapper[F[_, _]: Bitraverse, G[_]: Applicative, A, B](
  v: F[G[A], G[B]]
) {
  def bisequence = implicitly[Bitraverse[F]].bisequence(v)
}
implicit def bisequenceWrap[F[_, _]: Bitraverse, G[_]: Applicative, A, B](
  v: F[G[A], G[B]]
) = new BisequenceWrapper(v)

现在(some(1), some("a")).bisequence将编译得很好。

我想不出有什么好的理由Scalaz不包含这样的东西。在此期间是否添加它是一个品味问题,但让编译器在这里进行键入绝对没有理论障碍。

我认为cats版本在这里不会是多余的。

@ import cats.implicits._
import cats.implicits._
@ (4.some, 2.some).bisequence
res1: Option[(Int, Int)] = Some((4, 2))
@ (4.some, none).bisequence
res2: Option[Tuple2[Int, Nothing]] = None
  • Scala 2.13开始,Option#zip:在标准库中提供了这种精确的行为

    Some(2) zip Some('b') // Some((2, 'b'))
    Some(2) zip None      // None
    None zip Some('b')    // None
    None zip None         // None
    
  • Scala 2.13之前,Option#zip返回一个Iterable,可以将其与headOption:组合

    Some(2) zip Some('b') headOption // Some((2, 'b'))
    Some(2) zip None headOption      // None
    
scala> import scalaz._
import scalaz._
scala> import Scalaz._
import Scalaz._
scala> (Tuple2.apply[Int, Int] _).lift[Option].tupled
res5: (Option[Int], Option[Int]) => Option[(Int, Int)] = <function1>
scala> res5((some(3), some(11)))
res6: Option[(Int, Int)] = Some((3,11))
scala> res5((some(3), none))
res7: Option[(Int, Int)] = None

最新更新