Map on Scalaz Validation failure

青春壹個敷衍的年華 提交于 2019-12-06 17:05:59

问题


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]?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7516613/map-on-scalaz-validation-failure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!