Tuesday, September 16, 2008

ForEach the functional way.


Before I started my current job I worked as a software tester and did a lot of automated testing in python. I love working in python it takes most of the effort out of programming you just write down what you want and it compiles and runs. Down side is python is not a strongly typed language and I picked up some very bad habits form python. Which others have proceeded to beat out of me. One thing that python did have that I truly miss is the map function. It makes working on lists so much cleaner, and when you mix that with lambda you come out being able to do a lot of work in very few lines of code. A couple weeks ago I was talking with a friend of mine about how C# had no map functions and how if I had it I could shrink a bunch of code down to next to nothing. The following functions are the results of that conversation. At the time I didn't want to return a list at the time I was doing a lot of file maintenance and just wanted to traverse the folder structures in a clean way. So llama being the guy he is emailed me these two functions.

12 public static void ForEach<T>(this IEnumerable<T> list, Action<T> func)
13 {
14     foreach (T t in list)
15     {
16         func(t);
17     }
18 }
19 
20 public static void ForEach<T>(this IEnumerable<T> list, Action<T> func1, Action<T, Action<T>> func2)
21 {
22     foreach (T t in list)
23     {
24         func2(t, func1);
25     }
26 }

Here is an example of how they can be used.

14 public static void WalkFiles(string filePath, Action<string> workerFunc)
15 {
16     if (WalkFilesCont)
17     {
18         if (Directory.Exists(filePath))
19         {
20             System.IO.Directory.GetFiles(filePath).ForEach(workerFunc);
21             System.IO.Directory.GetDirectories(filePath).ForEach(workerFunc, WalkFiles);
22         }
23     }
24 }

I use them in a lot of other areas I even have one variation that behaves like a map in python I don't do much work on lists though where I need to see a result passed back so it doesn't get as much use. These first function gets used quite a bit more than I expected.

No comments: