Skip to content

Instantly share code, notes, and snippets.

@koropicot
Created September 8, 2013 08:52
Show Gist options
  • Save koropicot/6483060 to your computer and use it in GitHub Desktop.
Save koropicot/6483060 to your computer and use it in GitHub Desktop.
C#で部分適用を無理やり実現してみた改訂版 NYSL Version 0.9982
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) => string.Join(" ",new[]{s1,s2,s3,s4}));
var funcPartialApplied = func.Curry()("My")._()("is")._().Uncurry();
Console.WriteLine(funcPartialApplied("name","koropicot"));
}
}
public delegate TResult PartialApply<T,TResult>(T arg);
public static class PartialApply
{
//1引数関数
public static Func<T_, TResult> _<T_, TResult>(
this Func<T_, TResult> func)
{
return func;
}
//2引数関数
public static Func<T1,Func<T_,TResult>> _<T_,T1,TResult>(
this Func<T_,Func<T1,TResult>> func)
{
return v1 => _ => func(_)(v1);
}
//3引数関数
public static Func<T1,Func<T2, Func<T_, TResult>>> _<T_, T1, T2, TResult>(
this Func<T_, Func<T1,Func<T2, 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 class Func
{
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, T2, TResult> Uncurry<T1, T2, TResult>(this Func<T1, Func<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, T2, T3, TResult> Uncurry<T1, T2, T3, TResult>(this Func<T1, Func<T2, Func<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);
}
public static Func<T1, T2, T3, T4, TResult> Uncurry<T1, T2, T3, T4, TResult>(this Func<T1, Func<T2, Func<T3, Func<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