Home > Back-end >  how do we interpret => something => something2 => something3 in C#
how do we interpret => something => something2 => something3 in C#

Time:05-07

I am reading a book called functional programming in C# by Enrico Buonanno

public static Validator<T> FailFast<T>
   (IEnumerable<Validator<T>> validators)
   => t
   => validators.Aggregate(Valid(t), (acc, validator) => acc.Bind(_ => validator(t)));

The original text with the code above is:

The fail-fast strategy is easier to implement: Every validator returns a Validation, and Validation exposes a Bind function that only applies the bound function if the state is Valid (just like Option and Either), so we can use Aggregate to traverse the list of validators and Bind each validator to the running result.

The FailFast function takes a list of Validators and returns a Validator: a function that expects an object of type T to validate. On receiving the valid t, it traverses the list of validators using Valid(t) as accumulator (if the list of validators is empty, then t is valid) and applies each validator in the list to the accumulator with Bind.

There are three => signs. That makes me hard to understand the code well. Does anyone who is familiar with => operator and can explain it in plain English? Thanks a lot.

I also checked => operator in the documentation. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator but the demo in the doc is not as complicated as the code above.

CodePudding user response:

The => here mean different things, but in general each one denotes a lambda, anonymous function (with opt. closure) that is passed somewhere - usually as a parameter in a function call.

So, start with big obvious chunks of code like classes and top level methods, find mandatory () that indicate function calls, and it will probably be much easier to grasp.

First => is a shorthand form of method body (FailFast) to skip writing { } in small method for 'readability' (here: doubtful).
Second => is a lambda, created as the return value of the FailFast.
Third => is a lambda, passed as an argument to Aggregate().
Fourth => is a lambda, passed as an argument to Bind().

Adding some parentheses and adding top-level function brackets to make it more visible:

public static Validator<T> FailFast<T>(IEnumerable<Validator<T>> validators)
{
    return t => validators.Aggregate(Valid(t), ..secondparam..);
}

and the second param is:

(acc, validator) => acc.Bind(...anotherparam...)

and another param is:

_ => validator(t)

with t coming out from the scope of the lambda in return t=>.

  • Related