Skip to content

Instantly share code, notes, and snippets.

@koropicot
Last active December 22, 2015 13:59
Show Gist options
  • Save koropicot/6482811 to your computer and use it in GitHub Desktop.
Save koropicot/6482811 to your computer and use it in GitHub Desktop.
C#で部分適用を無理やり実現してみた。 NYSL Version 0.9982 追記 これScalaとかの動作と違ったので書き直す
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialApply
{
class Program
{
static void Main(string[] args)
{
var func = (Func<string, string, string, string, string>)((s1, s2, s3, s4) => s1 + s2 + s3 + s4);
var funcPartialApplied = func.Curry()._()(" on the wall, ")._()(".");
Console.WriteLine(funcPartialApplied("99 bottles of beer"));
}
}
public delegate TResult PartialApply<T,TResult>(T arg);
public static class PartialApply
{
//1引数関数
public static PartialApply<T_, TResult> _<T_, TResult>(
this Func<T_, TResult> func)
{
return new PartialApply<T_,TResult>(func);
}
public static PartialApply<T_, TResult> _<T_, TResult>(
this Func<T_, PartialApply<T_, TResult>> func)
{
return _ => func(_) (_);
}
//2引数関数
public static Func<T1,PartialApply<T_,TResult>> _<T_,T1,TResult>(
this Func<T_,Func<T1,TResult>> func)
{
return v1 => _ => func(_)(v1);
}
public static Func<T1, PartialApply<T_, TResult>> _<T_, T1, TResult>(
this Func<T_, Func<T1, PartialApply<T_, TResult>>> func)
{
return v1 => _ => func(_)(v1) (_);
}
//3引数関数
public static Func<T1,Func<T2, PartialApply<T_, TResult>>> _<T_, T1, T2, TResult>(
this Func<T_, Func<T1,Func<T2, TResult>>> func)
{
return v1 => v2 => _ => func(_)(v1)(v2);
}
public static Func<T1,Func<T2, PartialApply<T_, TResult>>> _<T_, T1, T2, TResult>(
this Func<T_, Func<T1,Func<T2, PartialApply<T_, TResult>>>> func)
{
return v1 => v2=> _ => func(_)(v1)(v2) (_);
}
//4引数関数
public static Func<T1, Func<T2,Func<T3, PartialApply<T_, TResult>>>> _<T_, T1, T2, T3, TResult>
(this Func<T_, Func<T1, Func<T2,Func<T3, TResult>>>> func)
{
return v1 => v2 => v3 => _ => func(_)(v1)(v2)(v3);
}
public static Func<T, TResult> ToFunc<T, TResult>(PartialApply<T, TResult> func)
{
return v => func(v);
}
}
public static class Func
{
public static Func<T1, TResult> Curry<T1, TResult>(this Func<T1, TResult> func)
{
return v1 => func(v1);
}
public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
{
return v1 => v2 => func(v1, v2);
}
public static Func<T1, Func<T2, Func<T3, TResult>>> Curry<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> func)
{
return v1 => v2 => v3 => func(v1, v2, v3);
}
public static Func<T1, Func<T2, Func<T3, Func<T4, TResult>>>> Curry<T1, T2, T3, T4, TResult>(this Func<T1, T2, T3, T4, TResult> func)
{
return v1 => v2 => v3 => v4 => func(v1, v2, v3, v4);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment