The Daily WTF
There are real advantages to taking a functional programming approach to expressing problems. Well, some problems, anyway.
Kevin sends us this example of elegant, beautiful functional code in C#:
//create a range of dates List<DateTime> dates = Enumerable.Range (0, 1 + settings.EndDate.Subtract (settings.BeginDate).Days).Select (offset => settings.BeginDate.AddDays(offset)).ToList(); foreach (DateTime procDate in dates) { /*.snip.*/ }
If you’re not sure what this code does, it’s okay- Kevin rewrote it and “ruined” it:
DateTime procDate = settings.BeginDate; while(procDate <= settings.EndDate) { /*.snip.*/ procDate= procDate.AddDays(1); }
The goal of this code is simply to do something for every day within a range of dates. These two approaches vary a bit in terms of readability though.
I guess the loop in the functional version isn’t mutating anything, I suppose. But honestly, I’m surprised that this didn’t take the extra step of using the .ForEach function (which takes a lambda and applies it to
To read the full article click on the 'post' link at the top.