Created
March 12, 2021 13:41
-
-
Save falfaddaghi/23479113a06cbb159733d8a5c57784a8 to your computer and use it in GitHub Desktop.
Curry in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ConsoleApp1 | |
{ | |
static class Program | |
{ | |
public static string FullName(string first, string last) | |
{ | |
return $"{first} {last}"; | |
} | |
public static string Greeter(string fullName, string message) | |
{ | |
return $"{message} {fullName}"; | |
} | |
static void Main(string[] args) | |
{ | |
Func<string, string, string> f = FullName; | |
Func<string, string, string> g = Greeter; | |
Func<string,Func<string,string>> fc = Curry<string,string,string>(FullName); | |
Func<string,Func<string,string>> gc = Curry<string,string,string>(Greeter); | |
//curried | |
var n1 = fc("first"); // this is now FullName("first", ??) where ?? will be filled in later (func<string,string>) | |
var fullName = n1("last"); //here we add the second parameter so now we get our final result | |
var g1 = gc(fullName); // same as above this is Greeter(fullName,??) where ?? will be filled in later (func<string,string>) | |
var g2 = g1("hello"); // here we add the second parameter | |
//normal flow | |
var name = FullName("foo", "bar"); | |
var greeting = Greeter(name, "hello"); | |
//normal | |
Console.WriteLine(greeting); | |
//curried | |
Console.WriteLine(g2); | |
} | |
//this method takes a function that takes 2 parameters and converts it to a function that takes | |
//a single parameter and returns a second function that will take the second parameter. | |
//basically it takes a function that takes 2 parameters and converts it into 2 | |
//functions that each take 1 parameter. | |
static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult> | |
(Func<T1, T2, TResult> function) | |
{ | |
return a => b => function(a, b); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment