Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Either usability improvements #1132

Merged
merged 1 commit into from
Jul 8, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions src/core/Akka/Util/Either.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
// </copyright>
//-----------------------------------------------------------------------

using System;

namespace Akka.Util
{
public abstract class Either<TA,TB>
Expand Down Expand Up @@ -39,8 +41,54 @@ public Left<TA, TB> ToLeft()
{
return new Left<TA, TB>(Left);
}

public static implicit operator Either<TA, TB>(Left<TA> left)
{
return new Left<TA, TB>(left.Value);
}

public static implicit operator Either<TA, TB>(Right<TB> right)
{
return new Right<TA, TB>(right.Value);
}

public Either<TRes1, TRes2> Map<TRes1, TRes2>(Func<TA, TRes1> map1, Func<TB, TRes2> map2)
{
if (IsLeft)
return new Left<TRes1, TRes2>(map1(ToLeft().Value));
return new Right<TRes1, TRes2>(map2(ToRight().Value));
}

public Either<TRes, TB> MapLeft<TRes>(Func<TA, TRes> map)
{
return Map(map, x => x);
}

public Either<TA, TRes> MapRight<TRes>(Func<TB, TRes> map)
{
return Map(x => x, map);
}

public TRes Fold<TRes>(Func<TA, TRes> left, Func<TB, TRes> right)
{
return IsLeft ? left(ToLeft().Value) : right(ToRight().Value);
}
}

public static class Either
{
public static Left<T> Left<T>(T value)
{
return new Left<T>(value);
}

public static Right<T> Right<T>(T value)
{
return new Right<T>(value);
}
}


public class Right<TA, TB> : Either<TA, TB>
{
public Right(TB b) : base(default(TA), b)
Expand All @@ -63,6 +111,26 @@ public override bool IsRight
}
}

public class Right<T>
{
public Right(T value)
{
Value = value;
}

public T Value { get; private set; }

public bool IsLeft
{
get { return false; }
}

public bool IsRight
{
get { return true; }
}
}

public class Left<TA, TB> : Either<TA, TB>
{
public Left(TA a) : base(a, default(TB))
Expand All @@ -84,5 +152,25 @@ public override bool IsRight
get { return Left; }
}
}

public class Left<T>
{
public Left(T value)
{
Value = value;
}

public T Value { get; private set; }

public bool IsLeft
{
get { return true; }
}

public bool IsRight
{
get { return false; }
}
}
}