Every Day – 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#:


List dates = Enumerable.Range
  (0, 1 + settings.EndDate.Subtract   
  (settings.BeginDate).Days).Select
  (offset => settings.BeginDate.AddDays(offset)).ToList();
foreach (DateTime procDate in dates)
{

}

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)
{

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 each parameter). Heck, with that approach, they could have done this whole thing in a single statement.

[Advertisement]
Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.

Source link

Stay in the Loop

Get the daily email from CryptoNews that makes reading the news actually enjoyable. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

You might also like...