Last active
April 28, 2023 16:32
-
-
Save leandromoh/72425a881c655223653bee3f18f00866 to your computer and use it in GitHub Desktop.
demonstrates how we use currying to fixe values in FP as well we do with object fields in OOP
This file contains 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; | |
var greeting = (string me, int age, string friend) => | |
$"Hello {friend}, my name is {me} and I am {age} years old"; | |
var f = greeting.Curry()("Ana")(13); | |
Console.WriteLine(f("Bob")); | |
Console.WriteLine(f("Carla")); | |
Console.WriteLine(); | |
var p = new Person("Ana", 13); | |
Console.WriteLine(p.Greeting("Bob")); | |
Console.WriteLine(p.Greeting("Carla")); | |
class Person | |
{ | |
public string Name; | |
public int Age; | |
public Person(string name, int age) | |
{ | |
Name = name; | |
Age = age; | |
} | |
public string Greeting(string friend) => | |
$"Hello {friend}, my name is {Name} and I am {Age} years old"; | |
} | |
public static class CurryExtension | |
{ | |
public static Func<T1, Func<T2, Func<T3, T4>>> Curry<T1,T2,T3,T4>(this Func<T1,T2,T3,T4> func) => | |
x => y => z => func(x, y, z); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By using currying to apply and fix some arguments we can hide the complexity of the original function (multiple parameters) and get a more simple and specialized version of the function (few parameters).
In certain way, it is the same thing that we do in OOP, but we fix values as fields of the object.
In FP languages where functions are the main type as well first class citizen and all functions are curried by default it sounds as natural and useful as objects in OOP languages;