scala - How to compose functions that return Validation? -
this follow-up previous question
suppose have 2 validating functions return either input if valid or error messages if not.
type status[a] = validationnel[string, a] val ispositive: int => status[int] = x => if (x > 0) x.success else s"$x not positive".failurenel val iseven: int => status[int] = x => if (x % 2 == 0) x.success else s"$x not even".failurenel
suppose need validate instance of case class x
:
case class x(x1: int, // should positive x2: int) // should
more need function checkx: x => status[x]
. moreover, i'd write checkx
composition of ispositive
, iseven
.
val checkx: x => status[x] = ({x => ispositive(x.x1)} |@| {x => iseven(x.x2)}) ((x.apply _).lift[status])
does make sense ?
how write checkx
composition of ispositive
, iseven
?
there lots of ways write this, following:
val checkx: x => status[x] = x => ispositive(x.x1).tuple(iseven(x.x2)).as(x)
or:
val checkx: x => status[x] = x => ispositive(x.x1) *> iseven(x.x2) *> x.point[status]
the key point want run 2 validations "effects" , return original value in new context. legitimate applicative operation, own implementation shows. there nicer ways write it.
Comments
Post a Comment