Suppose I want to implement functional composition, for example:
public Func<T,T> Compose<T>(Func<T,T> f, Func<T,T> g) { return new Func<T,T>( x => f(g(x))); }
Now in practice, I can use this Compose () fn as follows:
public String ToUpper(String s) { return s.ToUpper(); } public String Replicate(String s) { return s+s; } public void Run() { var h = Compose<String>(ToUpper, Replicate); System.Console.WriteLine("{0}", h("fred")); }
And the result is FREDFRED .
Is there a way to use simpler syntax to call Compose? I tried like this:
var h = Compose(ToUpper, Replicate);
... but I get a compilation error:
error CS0411: type arguments for the method "FunctionalTest.Compose (System.Func, System.Func)" cannot be taken out of use. Try explicitly specifying type arguments.
Itβs completely clear. I am wondering if it is possible to declare it differently and get the conclusion that it really works.
EDIT
Origin of the problem: I watched an online lecture on a functional programming course led by UC Berkley CS61A. (find it on youtube). I have no formal FP training, and I thought I could learn something. Prof uses a scheme, and he talks about how the + lisp scheme is purely functional languages ββand other languages ββless. He specifically identified Pascal, C, C ++, and Java (but not C #) as missing functionality, and said that it would be difficult to perform functional composition with these languages ββ("Do not stand on your head"). He argued that a function pointer (as available in C, C ++) does not match the entity function, a lambda. I understand.
Funny - he did not mention Javascript or C #, which I consider to be the main languages ββthat have pretty good functionality. (I do not know F #.)
I am curious that this is a lecture from last year - 14 months ago - and yet he does not seem to know about the functional aspects of the main modern languages.
So, I follow and do the exercises, but instead of using a scheme or lisp, I use C #. And also some of them in Javascript.
In any case, thanks to everyone for the quality answers.