Mixing extension methods, generics and lambda expressions

I port the Haskell / LiveScript each function to C # and I am having some problems. The signature of this function is (a β†’ Undefined) β†’ [a] β†’ [a] , and I work very well with typed and lambda expressions in Haskell or LS, but C # bothers me. The final use of this extension method should be:

 String[] str = { "Haskell", "Scheme", "Perl", "Clojure", "LiveScript", "Erlang" }; str.Each((x) => Console.WriteLine(x)); 

And with this, my conclusion should be:

 Haskell Scheme Perl Clojure LiveScript Erlang 

My current implementation of each :

 public static void Each<T>(this IEnumberable<T> list, Action closure) { foreach (var result in list) { Delegate d = closure; object[] parameters = { result }; d.DynamicInvoke(parameters); } } 

The problem is that here I just can not pass the parameter in my lambda expression. I can not do (x) => ...

How to pass parameters to lambda expression? It was very easy to work with first-class features in Haskell than with C #. I am just very confused.

For those who do not know the implementation of each , it is used for side effects, returns its own list and applies the closing iteration and passes each value of the list as an argument. Its implementation in PHP should be:

 public static function each($func) { // where $this->value is a list foreach ($this->value as $xs) { $func($xs); } return $this->value; // Or return $this; in case of method-chaining } 

Can someone help me? I was looking for him, but this is not clear to me. [And I do not want to use Linq]

+5
source share
1 answer

You need Action<T> instead of Action . You can also call it directly, instead of using DynamicInvoke :

 public static void Each<T>(this IEnumberable<T> list, Action<T> a) { foreach (var result in list) { a(result); } } 
+10
source

Source: https://habr.com/ru/post/1204944/


All Articles