Saturday, April 21, 2012

If Your Only Tool Is A Lambda, All Your Problems Will Look Like Can Be Tackled By Lambda Only

I love lambda, you love lambda, we all love lambda. When we neo-.NET kids encounters a problem that involves anything enumerable, we launch right away our lambda-fu into stratosphere, not even taking into account that there might be a simpler way to tackle the problem


For example, given a problem to sum all BigIntegers, we tend to solve it in lambda-ish way sort of way. But since a BigInteger lacks a Sum lambda/extension method, we are inclined to write it with what is available to us, i.e. we use Aggregate lambda:


using System;
using System.Linq;

using System.Numerics;

using System.Collections.Generic;


class Great 
{
 public static void Main() 
 {
  var bigInts = new List<System.Numerics.BigInteger>() {1, 2, 3, 4};

  var result = bigInts.Aggregate((currentSum, item)=> currentSum + item);
   
  Console.WriteLine(result);
 
 }
}



However, we forget that there's already a simpler alternative available to us, which is BigInteger's helper Add method. Given lambda's popularity, we tend to forget that lambdas can be fed with helper methods. If there's already a predefined helper method for a given problem, by all means use them to simplify things up. The code above could be rewritten by using predefined helper:

var bigInts = new List<System.Numerics.BigInteger>() {1, 2, 3, 4};

var result = bigInts.Aggregate(BigInteger.Add);   

Console.WriteLine(result);

Output:
10


So there we are, we can use predefined helper method, simple and has lesser noise. Lest we forgot, lambdas are just inlined delegates; so if there's already a predefined helper method that matches the lambda's delegate signature, feel free to use that helper method

No comments:

Post a Comment