concept Validation in category c#

appears as: Validation
Functional Programming in C#: How to write better C# code

This is an excerpt from Manning's book Functional Programming in C#: How to write better C# code.

  • Because Either is rather abstract, and because of the syntactic overhead of its two generic arguments, in practice it’s better to use a particularized version of Either, such as Validation and Exceptional.
  • Applicatives aren’t as commonly used as functors and monads, so why even bother? It turns out that although Apply can be defined in terms of Bind, it generally receives its own implementation, both for efficiency and because Apply can have interesting behavior that’s lost when you define Apply in terms of Bind. In this book I’ll show two monads for which the implementation of Apply has such interesting behavior: Validation, later in this chapter, and Task, in chapter 13.

    The first expression shows the successful creation of a PhoneNumber. In the second case, we’re passing an invalid country code and get a failure as expected. In the third case, both the country and number are invalid, and we get a validation with two errors—remember, the Invalid case of a Validation holds an IEnumerable<Error> precisely to capture multiple errors.

    But how are the two errors, which are returned by different functions, harvested in the final result? This is due to the implementation of Apply for Validation.

    Listing 8.19. Implementation of Apply for Validation
    Listing 8.21. Implementation of Bind for Validation
    public static Validation<R> Bind<T, R> (this Validation<T> val, Func<T, Validation<R>> f) => val.Match( Invalid: (err) => Invalid(err), Valid: (r) => f(r));