18
import scalaz._
import Scalaz._

"abc".parseInt

This will return a Validation[NumberFormatException, Int]. Is there a way I can apply a function on the failure side (such as toString) to get a Validation[String, Int]?

huynhjl
  • 41,520
  • 14
  • 105
  • 158

2 Answers2

19

There is a pair of methods <-: and :-> defined on MAB[M[_,_], A, B] that map on the left and right side of any M[A, B] as long as there is a Bifunctor[M]. Validation happens to be a bifunctor, so you can do this:

((_:NumberFormatException).toString) <-: "123".parseInt

Scala's type inference generally flows from left to right, so this is actually shorter:

"123".parseInt.<-:(_.toString)

And requires less annotation.

Apocalisp
  • 34,834
  • 8
  • 106
  • 155
  • Nice. I wonder wether the following could be useful in MAB: def bimap[C,D](first: A => C = identity[A] \_, second: B => D = identity[B] \_)(implicit b: Bifunctor[M]): M[C, D] = b.bimap(value, first, second). So we get "123".parseInt.bimap(\_.toString) – Didier Dupont Sep 22 '11 at 23:17
  • That would be awesome. Send a pull request. – Apocalisp Sep 23 '11 at 16:37
11

There is a functor on FailProjection. So you could do

v.fail.map(f).validation

(fail to type as FailProjection, validation to get out of it)

Alternatively

v.fold(f(_).failure, _.success)

Both a bit verbose. Maybe someone more familiar with scalaz can come up with something better

Apocalisp
  • 34,834
  • 8
  • 106
  • 155
Didier Dupont
  • 29,398
  • 7
  • 71
  • 90