Fold

Cria um novo valor do tipo TState aplicando a função folder ao valor either de acordo com seu estado.

Parâmetros

Retorno

Func<TState, TRight, TState> folderWhenRight

Func<TState, TLeft, TState> folderWhenLeft

TState state

Either<TLeft, TRight> either

TState

Como usar

Esta função realiza uma transformação de um Either<TLeft, TRight> para um TState ao aplicar a função folder respectiva ao seu estado.

Quando o valor Either está no estado IsRight

int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.Fold(
    state,
    (_state, right) => right + _state,
    (_state, left)  => _state + 10);

//result = 42

Quando o valor Either está no estado IsLeft

int state = 20
Either<string, int> eitherValue = "ERROR";
int result = eitherValue.Fold(
    state,
    (_state, right) => right + _state,
    (_state, left)  => _state + 10);

//result = 30

Abordagens para apenas um dos lados

Você pode utilizar os métodos FoldLeft e FoldRight para obter o mesmo resultado, mas desta vez aplicando a função em somente um dos valores.

Sempre que estas funções forem aplicados para valores Either que não estão do mesmo tipo que a função de avaliação será retornado o valor state informado por parâmetro.

FoldRight Quando o valor Either está no estado IsRight

int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.FoldRight(
    state,
    (_state, right) => right + _state);

//result = 42

FoldRight Quando o valor Either está no estado IsLeft

int state = 20
Either<string, int> eitherValue = "ERROR";
int result = eitherValue.FoldRight(
    state,
    (_state, right) => right + _state);

//result = 20

FoldLeft Quando o valor Either está no estado IsRight

int state = 20
Either<string, int> eitherValue = 22;
int result = eitherValue.FoldLeft(
    state,
    (_state, left) => _state + 10);

//result = 20

Last updated