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