使用 Scalaz 或 Shapeless 将选项元组转换为元组选项 [英] Converting a tuple of options to an option of tuple with Scalaz or Shapeless

查看:35
本文介绍了使用 Scalaz 或 Shapeless 将选项元组转换为元组选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有

(Some(1), Some(2))

我希望得到

Some((1, 2))

和拥有

(Some(1), None)

我希望得到

None

推荐答案

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

You can use the fact that Scalaz 7 provides a Bitraverse instance for tuples and then sequence as usual (but with bisequence instead of 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))

不幸的是,Scalaz 7 目前需要这里的类型注释.

Unfortunately Scalaz 7 currently needs the type annotation here.

在评论中,Yo Eight 声明类型注释在这里仍然是强制性的.我不确定他或她的推理是什么,但实际上编写自己的包装器非常容易,该包装器将提供具有 bisequence 方法的任何适当类型的元组,并且不需要类型注释:

In a comment Yo Eight states that the type annotation will remain mandatory here. I'm not sure what his or her reasoning is, but it's in fact perfectly easy to write your own wrapper that will provide any appropriately typed tuple with a bisequence method and won't require a type annotation:

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 将编译得很好.

Now (some(1), some("a")).bisequence will compile just fine.

我想不出一个很好的理由 Scalaz 不会包含这样的东西.在此期间是否要添加它是一个品味问题,但让编译器在此处进行输入绝对没有理论上的障碍.

I can't think of a good reason Scalaz wouldn't include something like this. Whether or not you want to add it in the meantime is a matter of taste, but there's definitely no theoretical obstacle to letting the compiler do the typing here.

这篇关于使用 Scalaz 或 Shapeless 将选项元组转换为元组选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆