.net - Building a chained set of method calls from a C# object in f# -
i'm learning f# , got thinking. can chain operations normal operators, such
let achainedfunc = list.map func >> list.reduce func
then later can go let result = achainedfunc alist
results of same operations, allowing nice reuse in short amount of code.
but, if have c# object want invoke methods object, pre-build chain f# example above?
obviously requires object can normal a.method1().method2().method3()
make work, there way sanely set allow work without building method pass in instead?
if wanted create sequence of static method calls (or extension method calls), sometype.method1
, sometype.method2
, othertype.method3
, can write c# method compose
behaves >>
operator in c#:
func<t, r> compose<t, u, r>(func<t, u> f1, func<u, r> f2) { return v => f2(f2(v)); }
then should able write like:
compose(sometype.method1, sometype.method2).compose(othertype.method3); // ...
note work methods taking single argument (but define overloaded versions take multiple arguments , compiler should able infer them).
if you're calling instance methods there no syntax referring method - need expression invoke method on. little lighter way writing method write lambda expression:
// chain multiple operations func<sometype, sometype> composed = v => v.method1().method2().method3(); // use chained operation 2 times var v1 = composed(foo1); var v2 = composed(foo2);
Comments
Post a Comment