ibcoleman
03/09/2021, 11:40 PMsuspend fun String.parseAgeString(): ValidatedNel<ValidationError, Int> =
this.parseToInt().mapLeft{ Nel.just(ValidationError.InvalidAge) }
But I’m having a hard time trying to figure out how to chain additional validation rules---say we have a Valid value but it has to be greater than 18 or it returns another distinct ValidationError.simon.vergauwen
03/10/2021, 11:46 AMValidated
values using mapN
which will become zip
to mimic the APIs of Kotlin Std.
So you can do:
fun validateAge(age: Int): ValidatedNel<ValidationError, Int> = ...
fun validateName(name: String): ValidatedNel<ValidationError, String> = ...
validateAge(29).zip(validateName("Simon"), ::Pair)
When using ValidatedNel
there would not even be the need anymore to pass Semigroup
only when you're doing so for an arbitrary E
.simon.vergauwen
03/10/2021, 11:47 AMsimon.vergauwen
03/10/2021, 11:47 AMzip
is Validated.applicative(NonEmptyList.semigroup<ValidationError>()).mapN(validateAge(29), validateName("Simon"), ::Pair)
ibcoleman
03/10/2021, 2:34 PMibcoleman
03/10/2021, 2:34 PMibcoleman
03/10/2021, 2:35 PMibcoleman
03/10/2021, 2:35 PMibcoleman
03/10/2021, 2:43 PMsuspend fun String.parseAgeString(): ValidatedNel<ValidationError, Int> =
this.parseToInt().mapLeft{ Nel.just(ValidationError.InvalidAgeNotAnInt) }
.somethingSomething{ age -> age <= 18 }.mapLeft{ Nel.just(ValidationError.InvalidAgeTooYoung }
I’m been down a rabbit-hole, so maybe just overcomplicating things… 🙂raulraja
03/10/2021, 3:15 PMmake sure it's an int, but also greater than 18
that is actually 2 validNel
values that would then be composed independently with one or many more validated valuesraulraja
03/10/2021, 3:17 PMibcoleman
03/10/2021, 3:31 PMresult.a
(the validated Int) here to do additional dependent validations, or if you have to parse the Int in parseAgeString()
then again in checkMinimumAge
val result = ValidatedNel.applicative(accumulator).tupledN(
age.parseAgeString(),
numberOfSpeedingTickets.parseTicketCountString()
).somethingSomething{ vals -> checkMinimumAge(vals.a) }
stojan
03/10/2021, 5:32 PMandThen
function for dependent validationraulraja
03/10/2021, 6:18 PMeither
block too as Validated
values have a bind operator there and they are treated just if it was an Either