Skip to content

Instantly share code, notes, and snippets.

@sheastrickland
Last active August 29, 2015 13:57
Show Gist options
  • Save sheastrickland/9801387 to your computer and use it in GitHub Desktop.
Save sheastrickland/9801387 to your computer and use it in GitHub Desktop.
Language extensions like .Safe, .Curry etc
using System;
using System.Collections.Generic;
namespace Awesomeness
{
public static class LanguageExtensions
{
public static TR? Safe<T, TR>(this T? target, Func<T, TR> accessor)
where T : struct where TR : struct
{
return target.HasValue ? accessor(target.Value) : default(TR?);
}
/// <see cref="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator" />
public static TR Safe<T, TR>(this T target, Func<T, TR> accessor)
where T : class
{
return target != null ? accessor(target) : default(TR);
}
/// <see cref="http://groovy.codehaus.org/Operators#Operators-ElvisOperator" />
public static TR Safe<T, TR>(this T target, Func<T, TR> accessor, TR @else)
where T : class
{
var result = target.Safe(accessor);
return EqualityComparer<TR>.Default.Equals(result, default(TR)) ? @else : result;
}
/// <example>
/// Func<int, int, bool> isGreater = (x, y) => x > y;
/// Func<int, bool> isGreaterThanTwo = isGreater.PartiallyEvaluateRight(2);
/// </example>
public static Func<TIn1, TOut> PartiallyEvaluateRight<TIn1, TIn2, TOut>(this Func<TIn1, TIn2, TOut> func, TIn2 in2)
{
return in1 => func(in1, in2);
}
/// <example>
/// Func<int, int, bool> greaterThan = (x, y) => x > y;
/// Func<int, Func<int, bool>> factory = greaterThan.Curry();
/// Func<int, bool> withTwo = factory(2); // makes y => 2 > y
/// </example>
public static Func<TIn1, Func<TIn2, TOut>> Curry<TIn1, TIn2, TOut>(this Func<TIn1, TIn2, TOut> func)
{
return in1 => in2 => func(in1, in2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment