Iterate
Apply the given function to Either<TLeft, TRight> value according to its state.
| Parameters | Returns |
|---|---|
|
Action<TRight> actionWhenRight Action<TRight> actionWhenLeft Either<TLeft, TRight> either |
void |
Usage
This function is an alternative to Map functions to apply an Action rather a Func delegate.
When Either IsRight
Either<string, int> either = 10;
either.Iterate(
right => Console.WriteLine(right.ToString()),
left => Console.WriteLine($"Hello {left}"));
//"10"
When Either IsLeft
Either<string, int> either = " World";
either.Iterate(
right => Console.WriteLine(right.ToString()),
left => Console.WriteLine($"Hello {left}"));
//"Hello World"
One sided approach
You can also use the IterateLeft and IterateRight to produce the same results, but with these methods the action is applied just to one of the possible values.
When the target type is different from Either current value the function will creates an Unit value.
IterateLeft when Either IsRight
Either<string, int> either = 10;
either.IterateLeft(left => Console.WriteLine($"Hello {left}"));
//
IterateLeft when Either IsLeft
Either<string, int> either = " World";
either.IterateLeft(
left => Console.WriteLine($"Hello {left}"));
//"Hello World"