Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# support function composition?

In the latest version of C#, can I do something like Haskell's function composition? more...?

Function composition is the act of pipelining the result of one function, to the input of another, creating an entirely new function.

I feel like linq is the closest but that's chaining, not function composition, right?

like image 208
Joan Venge Avatar asked Mar 10 '11 18:03

Joan Venge


People also ask

Does hep C go away?

It is highly curable ... Direct-acting antiviral medications — given over a 12-week period — actually can cure early acute hepatitis C better than 90% of the time.

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .


2 Answers

public static class Extensions {     public static Func<T, TReturn2> Compose<T, TReturn1, TReturn2>(this Func<TReturn1, TReturn2> func1, Func<T, TReturn1> func2)     {         return x => func1(func2(x));     } } 

Usage:

Func<int, int> makeDouble = x => x * 2; Func<int, int> makeTriple = x => x * 3; Func<int, string> toString = x => x.ToString(); Func<int, string> makeTimesSixString = toString.Compose(makeDouble).Compose(makeTriple);  //Prints "true" Console.WriteLine(makeTimesSixString (3) == toString(makeDouble(makeTriple(3)))); 
like image 90
Davy8 Avatar answered Oct 05 '22 22:10

Davy8


I did not let the compiler check this, but this should be possible:

public static Func<T3,T1> my_chain<T1, T2, T3>(Func<T2,T1> f1, Func<T3,T2> f2) {     return x => f2(f1(x)); } 
like image 35
Doc Brown Avatar answered Oct 05 '22 23:10

Doc Brown