Skip to content

Instantly share code, notes, and snippets.

@siliconbrain
Last active May 8, 2018 03:03
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save siliconbrain/3923828 to your computer and use it in GitHub Desktop.
Save siliconbrain/3923828 to your computer and use it in GitHub Desktop.
Implemetation of Haskell's Either type in C#
/// <summary>
/// Interface definition of Either
/// </summary>
/// <typeparam name="Tl">type of the Left value</typeparam>
/// <typeparam name="Tr">type of the Right value</typeparam>
public interface IEither<out Tl, out Tr>
{
/// <summary>
/// Check the type of the value held and invoke the matching handler function
/// </summary>
/// <typeparam name="U">the return type of the handler functions</typeparam>
/// <param name="ofLeft">handler for the Left type</param>
/// <param name="ofRight">handler for the Right type</param>
/// <returns>the value returned by the invoked handler function</returns>
U Case<U>(Func<Tl, U> ofLeft, Func<Tr, U> ofRight);
/// <summary>
/// Check the type of the value held and invoke the matching handler function
/// </summary>
/// <param name="ofLeft">handler for the Left type</param>
/// <param name="ofRight">handler for the Right type</param>
void Case(Action<Tl> ofLeft, Action<Tr> ofRight);
}
/// <summary>
/// Static helper class for Either
/// </summary>
public static class Either
{
private sealed class LeftImpl<Tl, Tr> : IEither<Tl, Tr>
{
private readonly Tl value;
public LeftImpl(Tl value)
{
this.value = value;
}
public U Case<U>(Func<Tl, U> ofLeft, Func<Tr, U> ofRight)
{
if (ofLeft == null)
throw new ArgumentNullException("ofLeft");
return ofLeft(value);
}
public void Case(Action<Tl> ofLeft, Action<Tr> ofRight)
{
if (ofLeft == null)
throw new ArgumentNullException("ofLeft");
ofLeft(value);
}
}
private sealed class RightImpl<Tl, Tr> : IEither<Tl, Tr>
{
private readonly Tr value;
public RightImpl(Tr value)
{
this.value = value;
}
public U Case<U>(Func<Tl, U> ofLeft, Func<Tr, U> ofRight)
{
if (ofRight == null)
throw new ArgumentNullException("ofRight");
return ofRight(value);
}
public void Case(Action<Tl> ofLeft, Action<Tr> ofRight)
{
if (ofRight == null)
throw new ArgumentNullException("ofRight");
ofRight(value);
}
}
/// <summary>
/// Create an Either with Left value
/// </summary>
/// <typeparam name="Tl">type of the Left value</typeparam>
/// <typeparam name="Tr">type of the Right value</typeparam>
/// <param name="value">the value to hold</param>
/// <returns>an Either with the specified Left value</returns>
public static IEither<Tl, Tr> Left<Tl, Tr>(Tl value)
{
return new LeftImpl<Tl, Tr>(value);
}
/// <summary>
/// Create an Either with Right value
/// </summary>
/// <typeparam name="Tl">type of the Left value</typeparam>
/// <typeparam name="Tr">type of the Right value</typeparam>
/// <param name="value">the value to hold</param>
/// <returns>an Either with the specified Right value</returns>
public static IEither<Tl, Tr> Right<Tl, Tr>(Tr value)
{
return new RightImpl<Tl, Tr>(value);
}
/// <summary>
/// Create an Either with the specified value
/// </summary>
/// <typeparam name="Tl">type of the Left value</typeparam>
/// <typeparam name="Tr">type of the Right value</typeparam>
/// <param name="value">the value to hold</param>
/// <returns>an Either with the specified value</returns>
public static IEither<Tl, Tr> Create<Tl, Tr>(Tl value)
{
return new LeftImpl<Tl, Tr>(value);
}
/// <summary>
/// Create an Either with the specified value
/// </summary>
/// <typeparam name="Tl">type of the Left value</typeparam>
/// <typeparam name="Tr">type of the Right value</typeparam>
/// <param name="value">the value to hold</param>
/// <returns>an Either with the specified value</returns>
public static IEither<Tl, Tr> Create<Tl, Tr>(Tr value)
{
return new RightImpl<Tl, Tr>(value);
}
}
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
@jjstaats
Copy link

jjstaats commented Jun 3, 2015

This code is missing a licence. May I uses this code for a project I'am working on?

@siliconbrain
Copy link
Author

I know it comes a little late, but I added a license at the end of the code.

@sethveale
Copy link

sethveale commented May 8, 2018

Hi - modified it to be a bit less documented and more idiomatic (for C#).
Also added support for C# 7's pattern matching.
Yours is a very practical C# Either so I've essentially just tweaked it to match the language a bit more.

/// <summary>
///     Pattern matching interface for LHS of <see cref="IEither{TLeft,TRight}" />
/// </summary>
public interface ILeft<out TLeft>
{
    TLeft Value { get; }
}

/// <summary>
///     Pattern matching interface for RHS of <see cref="IEither{TLeft,TRight}" />
/// </summary>
public interface IRight<out TRight>
{
    TRight Value { get; }
}

/// <summary>
///     Either monad converted to non-functional C# idioms
/// </summary>
public interface IEither<out TLeft, out TRight>
{
    TReturn Select<TReturn>(Func<TLeft, TReturn> ofLeft, Func<TRight, TReturn> ofRight);

    void Do(Action<TLeft> ofLeft, Action<TRight> ofRight);

    /// <summary>
    ///     Provides the left value
    /// </summary>
    /// <exception cref="InvalidOperationException">if this is a right value</exception>
    TLeft Left();

    /// <summary>
    ///     Provides the right value
    /// </summary>
    /// <exception cref="InvalidOperationException">if this is a left value</exception>
    TRight Right();
}

/// <summary>
///     Static helper class for Either
/// </summary>
public static class Either
{
    private struct LeftImpl<TLeft, TRight> : IEither<TLeft, TRight>, ILeft<TLeft>
    {
        public TLeft Value { get; }
        public TLeft Left() => Value;
        public TRight Right() => throw new InvalidOperationException();

        public LeftImpl(TLeft value)
        {
            Value = value;
        }

        public TReturn Select<TReturn>(Func<TLeft, TReturn> ofLeft, Func<TRight, TReturn> ofRight)
        {
            if (ofLeft == null)
                throw new ArgumentNullException(nameof(ofLeft));

            return ofLeft(Value);
        }

        public void Do(Action<TLeft> ofLeft, Action<TRight> ofRight)
        {
            if (ofLeft == null)
                throw new ArgumentNullException(nameof(ofLeft));

            ofLeft(Value);
        }
    }

    private struct RightImpl<TLeft, TRight> : IEither<TLeft, TRight>, IRight<TRight>
    {
        public TRight Value { get; }
        public TLeft Left() => throw new InvalidOperationException();
        public TRight Right() => Value;

        public RightImpl(TRight value)
        {
            Value = value;
        }

        public TReturn Select<TReturn>(Func<TLeft, TReturn> ofLeft, Func<TRight, TReturn> ofRight)
        {
            if (ofRight == null)
                throw new ArgumentNullException(nameof(ofRight));

            return ofRight(Value);
        }

        public void Do(Action<TLeft> ofLeft, Action<TRight> ofRight)
        {
            if (ofRight == null)
                throw new ArgumentNullException(nameof(ofRight));

            ofRight(Value);
        }
    }

    /// <summary>
    ///     Create an Either with Left value
    /// </summary>
    public static IEither<TLeft, TRight> Left<TLeft, TRight>(TLeft value)
    {
        return new LeftImpl<TLeft, TRight>(value);
    }

    /// <summary>
    ///     Create an Either with Right value
    /// </summary>
    public static IEither<TLeft, TRight> Right<TLeft, TRight>(TRight value)
    {
        return new RightImpl<TLeft, TRight>(value);
    }
}

@sethveale
Copy link

With this you can do things like:

IEither<string, bool> someEither = ...;
switch(someEither)
{
    case ILeft<string> left: Console.WriteLine("Woo!"); break;
    case IRight<bool> right: Console.WriteLine("Yay!"); break;
}

Likewise, were we to do the standard Try either thing with the exceptions in the left value, exceptions from multiple eithers can be handled together since the ILeft interface is independent of IEither.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment