ap<A, B, C> function
- Either<
A, B Function(C)> fnEither
Applies a function inside an Either to a value inside another Either.
This function takes an Either that may contain a function of type B Function(C) and applies it to a value inside another Either of type Either<A, C>.
If the first Either is a Left<A>, the resultant Either will also be a Left<A>.
If the second Either is a Left<A>, the resultant Either will also be a Left<A>, irrespective of the first Either's value.
Example:
Given an Either that might contain a function:
Either<int, int Function(String)> fnEither = Right((s) => s.length);
And another Either that might contain a string:
Either<int, String> valueEither = Right("Bob");
You can use the ap function to apply the function inside fnEither to the value inside valueEither:
final result = ap(fnEither)(valueEither);
if (result is Right<int>) {
print("String length is ${result.value}");
} else if (result is Left<int>) {
print("Error code: ${result.value}");
}
In this example, the output will be:
String length is 3
If either fnEither or valueEither were a Left<int>, the output would display the error code.
@param fEither The Either that may contain a function of type B Function(C).
@return A function that takes an Either<A, C> and returns an Either<A, B>.
Implementation
Either<A, B> Function(Either<A, C>) ap<A, B, C>(
Either<A, B Function(C)> fnEither) =>
(Either<A, C> either) => flatMap<A, B Function(C), B>((B Function(C) fn) {
return match<A, C, Either<A, B>>(
(a) => Left<A, B>(a), (c) => Right<A, B>(fn(c)))(either);
})(fnEither);