Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))

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)

It struck me as a very common thing to want to do. Is there any sugar in scalaz that does this ?

like image 241
Hassan Syed Avatar asked Mar 18 '23 17:03

Hassan Syed


1 Answers

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.

What you're looking for is probably traverse (or traverseU if you want to avoid writing out the type parameters). 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).

like image 63
Travis Brown Avatar answered Mar 21 '23 05:03

Travis Brown