Does c#'s type system have the ability to specify a function that takes an enumerable number of functions which commute to form a pipeline?
The effect would be similar to chaining, but instead of
var pipeline = a.Chain(b).Chain(c)
one could write
var pipeline = CreatePipeline(a,b,c)
where a, b and c are functions? I have included a bit of sample code to illustrate, thanks.
void Main()
{
Func<int, string> a = i => i.ToString();
Func<string, DateTime> b = s => new DateTime(2000,1,1).AddDays(s.Length);
Func<DateTime, bool> c = d => d.DayOfWeek == DayOfWeek.Wednesday;
//var myPipeline = CreatePipeline(a, b, c);
Func<int, bool> similarTo = i => c(b(a(i))) ;
Func<int, bool> isThisTheBestWeCanDo = a.Chain(b).Chain(c);
}
public static class Ext{
//public static Func<X, Z> CreatePipeline<X,Z>(params MagicFunc<X..Y>[] fns) {
// return
//}
public static Func<X, Z> Chain<X,Y,Z>(this Func<X,Y> a, Func<Y,Z> b)
{
return x => b(a(x));
}
}
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C is a high-level and general-purpose programming language that is ideal for developing firmware or portable applications. Originally intended for writing system software, C was developed at Bell Labs by Dennis Ritchie for the Unix Operating System in the early 1970s.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
You can consider this solution:
public class Pipeline
{
public Func<object, object> CreatePipeline(params Func<object, object>[] funcs)
{
if (funcs.Count() == 1)
return funcs[0];
Func<object, object> temp = funcs[0];
foreach (var func in funcs.Skip(1))
{
var t = temp;
var f = func;
temp = x => f(t(x));
}
return temp;
}
}
Usage:
Func<int, string> a = x => (x * 3).ToString();
Func<string, bool> b = x => int.Parse(x.ToString()) / 10 > 0;
Func<bool, bool> c = x => !x;
var pipeline = new Pipeline();
var func = pipeline.CreatePipeline(x => a((int)x), x => b((string)x), x => c((bool)x));
Console.WriteLine(func(3));//True
Console.WriteLine(func(4));//False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With