Fold
Creates a new TState value by applying the given folder functions to state and Either<TLeft, TRight> value according to its state.
Parameters
Returns
Func<TState, TRight, TState> folderWhenRight
Func<TState, TLeft, TState> folderWhenLeft
TState state
Either<TLeft, TRight> either
TState
Usage
This function applies the folder function to the Either<TLeft, TRight> value and to the state according its state.
When Either IsRight
int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.Fold(
state,
(_state, right) => right + _state,
(_state, left) => _state + 10);
//result = 42When Either IsLeft
int state = 20
Either<string, int> eitherValue = "ERROR";
int result = eitherValue.Fold(
state,
(_state, right) => right + _state,
(_state, left) => _state + 10);
//result = 30One sided approach
You can also use the FoldLeft and FoldRight to produce the same results, but with these methods the folder is applied just to one of the possible values.
When the target type is different from Either current value the result always will be equals to state.
FoldRight when Either IsRight
int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.FoldRight(
state,
(_state, right) => right + _state);
//result = 42FoldRight when Either IsLeft
int state = 20
Either<string, int> eitherValue = "ERROR";
int result = eitherValue.FoldRight(
state,
(_state, right) => right + _state);
//result = 20FoldLeft Either IsRight
int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.FoldLeft(
state,
(_state, left) => _state + 10);
//result = 20Last updated
Was this helpful?