Reputation:
So I am trying to implement this definition:-
def validate(validationPredicates: List[A => Try[Boolean]]): Try[Boolean] = ???
And the way its supposed to work is the follows:-
Accept a list of predicates (with different args for each predicate, so A is technically wrong).
Run through each of them. The methods that are put in here can either return true, false or throw an exception.
Stop the run through each of them when we either see a false, or see an exception in the sequence.
There are other things going on here (other kinds of side effects in the individual validators, but that will not impact the chain of operations).
Can someone tell me how to implement the chain AND the syntax for accepting functions of any input args but output always Try[Boolean]?
Upvotes: 0
Views: 103
Reputation: 27356
I may be missing something, but isn't this just
Try(validationPredicates.forall(_(a).get))
If all predicates return Success(true)
you will get Success(true)
If any predicate returns Success(false)
you will get Success(false)
and no more predicates will be tested
If any predicate returns Failed(e)
, the .get
will re-throw the exception which is caught by the outer Try and you will get Failed(e)
This assumes that the functions return Try[Boolean]
. If they just return Boolean
(as described in the text) then just remove the .get
I haven't addressed the remark about "the syntax for accepting functions of any input args" because I don't know what it means, and feels like a separate question.
Upvotes: 1
Reputation: 1678
def validate[A](validationPredicates: List[A => Try[Boolean]]): A => Try[Boolean] =
(a: A) => validationPredicates.foldLeft(Try(true))(
(state, predicate) => state.flatMap(bool => predicate(a).map(_ && bool))
)
In cats world, you are looking for traverse
Upvotes: 2