Bind
Creates a new Option<T>
whose value is the result of applying the given binder
function to Option<T>.Some
value when option IsSome
.
Otherwise returns an Option<T>.None()
.
Parameters
Returns
Func<T, Option<TResult>> binder
Option<T> option
Option<TResult>
Como usar
This function is usually used to modify an option value by using an function that receive a regular value and returns an optional.
It works like a Map
function, but in this case the function returns an option value.
When the option value IsSome and binder returns IsSome
Option<int> SquareWhenEven(int value)
{
if(element % 2 == 0)
return value * value;
else
return Option<int>.None();
}
Option<int> optionValue = 4;
Option<int> result = optionValue.Bind(SquareWhenEven);
//result.IsSome = true
//result.Some = 8
When the option value IsSome and binder returns IsNone
Option<int> SquareWhenEven(int value)
{
if(element % 2 == 0)
return value * value;
else
return Option<int>.None();
}
Option<int> optionValue = 5;
Option<int> result = optionValue.Bind(SquareWhenEven);
//result.IsSome = false
//result.IsNone = true
When the option value IsNone
Option<int> SquareWhenEven(int value)
{
if(element % 2 == 0)
return value * value;
else
return Option<int>.None();
}
Option<int> optionValue = Option<int>.None();
Option<int> result = optionValue.Bind(SquareWhenEven);
//result.IsSome = false
//result.IsNone = true
Last updated
Was this helpful?