language-ext monad logical axioms in csharp

Axioms are the fundamental properties of any mathematical structure that operate in a given domain. Monad axioms describe the set of rules a monad needs to follow to truly be a monad.

In language-ext, a monad has to follow the following axioms to be considered a monad:

  1. Left identity (return unit >>= f ≡ f)

    A monad's left identity requires that the return method acts like a neutral element for the bind operation >>=. In other words, when you return a value from a monad, you should be able to apply any function f to that value using bind >>= and get an equivalent result.

    main.cs
    public static class LeftIdentity
    {
        public static Try<int> LeftIdentityLaw(int x) =>
            Try(() => x).Bind(Try);
    }
    
    122 chars
    6 lines
  2. Right identity (m >>= return ≡ m)

    A monad's right identity requires that the bind operation >>= acts like a neutral element for the return method. In other words, when you apply bind >>= to a monad and pass return as a function, you should get the original monad back.

    main.cs
    public static class RightIdentity
    {
        public static Try<int> RightIdentityLaw(Try<int> m) =>
            m.Bind(Try) == m;
    }
    
    123 chars
    6 lines
  3. Associativity ((m >>= f) >>= g ≡ m >>= (x => f(x) >>= g))

    A monad's associativity requires that the bind operation >>= is associative. In other words, when you apply a chain of sequential bind operations, the order of execution should not matter.

    main.cs
    public static class Associativity
    {
        public static Try<int> AssociativityLaw(int x) =>
            Try(() => x).Bind(y => Try(() => y * 2)).Bind(z => Try(() => z / 2)) ==
            Try(() => x).Bind(y => Try(() => y * 2).Bind(z => Try(() => z / 2)));
    }
    
    250 chars
    7 lines

By following these axioms, you can ensure that any monad you build in language-ext is truly a monad and can benefit from all the properties of monads, like compositionality and modularity.

gistlibby LogSnag