[英]Scalaz flipping nested existential / validation mono-whatevers-nads around pre-applicative-building
I've got the following : 我有以下内容:
gt.map(_.singleVal) |@| lt.map(_.singleVal)
They are of type Option(Validation(T))
but they should be Validation(Option(T))
它们是Option(Validation(T))
但它们应该是Validation(Option(T))
It is ok for something to not exist, but it is not ok for something that exists to be invalid. 某些东西不存在是可以的,但是存在无效的东西是不行的。 In other words I would want None
to be interpreted as Success(None)
换句话说,我希望将None
解释为Success(None)
It struck me as a very common thing to want to do. 这让我感到非常普遍。 Is there any sugar in scalaz that does this ? scalaz中有没有这样做的糖吗?
I'm going to assume that by Validation(T)
you mean something like ValidationNel[Throwable, T]
, since Validation[T]
isn't anything and Validation[E, T]
doesn't have an applicative functor instance unless E
has a semigroup instance. 我将假设通过Validation(T)
你的意思是像ValidationNel[Throwable, T]
,因为Validation[T]
不是任何东西, Validation[E, T]
没有应用程序仿函数实例,除非E
有一个半群实例。
What you're looking for is probably traverse
(or traverseU
if you want to avoid writing out the type parameters). 什么你要找的可能是traverse
(或traverseU
如果你想避免编写出来的类型参数)。 You can write the following, for example: 您可以编写以下内容,例如:
scala> case class Foo(singleVal: ValidationNel[Throwable, String])
defined class Foo
scala> val x = some(Foo("hey".success))
x: Option[Foo] = Some(Foo(Success(hey)))
scala> val y = none[Foo]
y: Option[Foo] = None
scala> println(x.traverseU(_.singleVal))
Success(Some(hey))
scala> println(y.traverseU(_.singleVal))
Success(None)
In general if M
has a Traverse
instance and N
has an applicative functor instance, you can transform a M[A]
into a N[M[B]]
given a function A => N[B]
with traverse
(see my answer here for some additional discussion). 一般来说,如果M
有一个Traverse
实例而N
有一个applicative functor实例,你可以用一个函数A => N[B]
用traverse
将M[A]
转换为N[M[B]]
(参见我的答案)进行一些额外的讨论)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.