Created
September 9, 2010 13:48
-
-
Save zeedunk/571876 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace Foo | |
{ | |
[TestClass] | |
public class ReduceExamples | |
{ | |
[TestMethod] | |
public void Aggregate_Is_A_Poorly_Named_Version_Of_Reduce() | |
{ | |
var intList = new[] { 1, 2, 3 }; | |
var reduced = intList.Aggregate(10, ((x, y) => x * y)); | |
Assert.AreEqual(60, reduced); | |
} | |
/* | |
THIS SOLUTION ASSUMES AN ORDERED ENUMERATION | |
*/ | |
[TestMethod] | |
public void Count_Dupes_Imperative() | |
{ | |
var intList = new[] { 1, 1, 2, 2, 3, 4, 4 }; | |
var lastValue = 0; | |
var numOfDupes = 0; | |
foreach (var i in intList) | |
{ | |
if (i == lastValue) | |
{ | |
numOfDupes++; | |
} | |
lastValue = i; | |
} | |
Assert.AreEqual(3, numOfDupes); | |
} | |
/* | |
THESE SOLUTIONS DO NOT ASSUME AN ORDERED LIST | |
*/ | |
[TestMethod] | |
public void Count_Dupes_Somewhat_Declarative() | |
{ | |
var intList = new[] { 1, 2, 1, 2, 3, 4, 4 }; | |
var numOfDupes = 0; | |
foreach (var i in intList.Distinct()) | |
{ | |
if (intList.Count(x => x == i) > 1) numOfDupes++; | |
} | |
Assert.AreEqual(3, numOfDupes); | |
} | |
[TestMethod] | |
public void Count_Dupes_More_Declarative() | |
{ | |
var intList = new[] { 4, 1, 2, 2, 3, 4, 1 }; | |
var numOfDupes = intList.Distinct(). | |
Aggregate(0, ((dupes, item) => (intList.Count(x => x == item) > 1) ? dupes + 1 : dupes)); | |
Assert.AreEqual(3, numOfDupes); | |
} | |
[TestMethod] | |
public void Simpler_Version() | |
{ | |
var intList = new[] { 4, 1, 2, 2, 3, 4, 1 }; | |
var numOfDupes = intList.Distinct().Where(x => intList.Count(i => i == x) > 1).Count(); | |
Assert.AreEqual(3, numOfDupes); | |
} | |
} | |
} |
Not that it matters for most implementations, but the simpler version has worse performance characteristics than the version using aggregate. I'd guess it's because of count.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The tests are there in the order they are because they demonstrate my refactoring process toward the final function.