I made an extension method to find the number of consecutive values in a collection. Because it is generic, I allow the caller to define the “incrementor” which is a Func<> that is supposed to increment the value in order to check for the existence of a “next” value.
However, if the caller passes an improper incrementor (i.e. x => x), it will cause an infinite recursive loop. Any suggestions on a clean way to prevent this?
public static int CountConsecutive<T>(this IEnumerable<T> values, T startValue, Func<T, T> incrementor)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
if (incrementor == null)
{
throw new ArgumentNullException("incrementor");
}
var nextValue = incrementor(startValue);
return values.Contains(nextValue)
? values.CountConsecutive(nextValue, incrementor) + 1
: 1;
}
In the purest sense, this is an attempt at the Halting Problem and is undecidable. For all but the simplest cases, you’ll have to trust those calling your method.
Like others have shown, you can do a simple check of equality to show that the next value is different. Storing every visited
Twill work but you’ll have to worry about memory eventually.As an aside, here’s an easily implemented StackOverflowException so you have to be wary of any data set that will have a lot on consecutive values.