Morten Andersen-Gott
09/23/2021, 12:26 PMandThen
which would be nice to have in arrow. Currently one can achieve something functionally equal with withEither
like this:
Validated.catch { "0".toInt() }.toValidatedNel().withEither { it.flatMap { Either.catch { 1 / it } }
however going through an either instance feels unnecessary when one is still operating on validations. So perhaps something like this:
fun <E,A, B> Validated<E, A>.andThen(f: (A) -> Validated<E, B>) :Validated<E, B> {
return when(this){
is Valid -> f(value)
is Invalid -> this
}
}
Validated.catch { "0".toInt() }.toValidatedNel().andThen { Validated.catch { 1/it } }
Example is a simple, but it is quite useful when you want to do input validation first, and then if valid continue with more advanced validation rulessimon.vergauwen
09/23/2021, 12:29 PMeither { }
DSL to bind
Validated
in the same style a either
(using short-circuit).
So that gives you the same behavior as andThen
or going through Either
without actually paying for it. (it just folds under the hood).
either {
val x = Validated.catch { "0".toInt() }.bind()
val y = Validated.catch { 1 / x }.bind()
y
}
simon.vergauwen
09/23/2021, 12:29 PMValidated
programs in the style you mention.simon.vergauwen
09/23/2021, 12:30 PMValidated
like this would hurt.
As you’ve shown here withEither { }
is a bit cumbersome.Morten Andersen-Gott
09/24/2021, 6:16 AMsimon.vergauwen
09/24/2021, 6:24 AMMorten Andersen-Gott
09/27/2021, 9:32 AMsimon.vergauwen
09/27/2021, 9:33 AME
and you can by-pass the restriction of out E
as defined in the class
.Javier
09/27/2021, 8:48 PMJavier
09/27/2021, 8:49 PMValid(5) andThen Valid(10)
Javier
09/27/2021, 8:50 PMValid(5) then Valid(10)
Morten Andersen-Gott
09/28/2021, 6:25 AMsimon.vergauwen
09/28/2021, 6:27 AMinfix
, but when working with lambdas I don’t find them super useful.
I don’t think Valid(5) andThen { x: X -> Valid(x + 1) }
reads much better then Valid(5).andThen { }
but that can be left up to the user. It’s an approach we haven’t commonly taking since this breaks chain-ability.
Valid(5) andThen { x: X -> Valid(x + 1) }.map { it + 3 }
this code is invalid.
(Valid(5) andThen { x: X -> Valid(x + 1) }).map { it + 3 }
now this code is valid.simon.vergauwen
09/28/2021, 6:27 AMMorten Andersen-Gott
09/28/2021, 6:30 AM/vendor/bundle/ruby/3.0.0/gems/kramdown-1.17.0/lib/kramdown/parser/html.rb:10:in require: cannot load such file -- rexml/parsers/baseparser (LoadError)
), so haven’t been able to do a visual review of the generated docs.simon.vergauwen
09/28/2021, 6:31 AM