Skip to content

Instantly share code, notes, and snippets.

@bruno-cadorette
Created September 12, 2015 22:52
Show Gist options
  • Save bruno-cadorette/ec74821e190a96d7a43f to your computer and use it in GitHub Desktop.
Save bruno-cadorette/ec74821e190a96d7a43f to your computer and use it in GitHub Desktop.
using System;
namespace CSharpFunctional
{
[Serializable]
public class NoPatternException : Exception
{
public NoPatternException() { }
public NoPatternException(string message) : base(message) { }
public NoPatternException(string message, Exception inner) : base(message, inner) { }
protected NoPatternException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
public class PatternMatching<T, TResult> where T : class
{
private T _Value;
private TResult _Result;
private bool _IsDone;
public PatternMatching(T value)
{
_Value = value;
_Result = default(TResult);
_IsDone = false;
}
public PatternMatching(TResult result)
{
_Value = null;
_Result = result;
_IsDone = true ;
}
public static PatternMatching<T, TResult> Match(T valueToMatch)
{
return new PatternMatching<T, TResult>(valueToMatch);
}
public PatternMatching<T, TResult> Case<U>(Func<U, TResult> action) where U : class, T
{
return Case(action, x => true);
}
public PatternMatching<T, TResult> Case<U>(Func<U, TResult> action, Predicate<U> guard) where U : class, T
{
if(_IsDone)
{
return new PatternMatching<T, TResult>(_Result);
}
var x = _Value as U;
if (x != null && guard(x))
{
return new PatternMatching<T, TResult>(action(x));
}
else
{
return new PatternMatching<T, TResult>(_Value);
}
}
public PatternMatching<T, TResult> Default(Func<T, TResult> action)
{
if (_IsDone)
{
return new PatternMatching<T, TResult>(_Result);
}
else
{
return new PatternMatching<T, TResult>(action(_Value));
}
}
public TResult Get()
{
if(!_IsDone)
{
throw new NoPatternException();
}
return _Result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment