J
jehugaleahsa
Hello:
Yesterday, I encountered an interesting side-effect of iterators. Even
though the code looked fine, it actually was completely wrong. See if
you can figure out why this code doesn't do as it is expected and how
to fix it:
// Returns indicies of matching items
public static IEnumerable<int> FindAll(IList<T> list, Predicate<T>
predicate)
{
for (int i = 0; i != list.Count; ++i)
{
if (predicate(list))
{
yield return i;
}
}
}
// Removes the items in the IList at the given indicies (if it's not
an T[])
public static void RemoveAt(IList<T> list, IEnumerable<int> indicies)
{
int shift = 0;
foreach (int index in indicies)
{
list.RemoveAt(index - shift);
++shift;
}
}
// Caller
List<int> values = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8,
9 });
IEnumerable<int> indicies = FindAll<int>(values, delegate (int
current) { return i % 2 == 0; });
RemoveAt(values, indicies);
I just forced the RemoveAt method to take the predicate, but there is
a way to fix the caller withouth touching the other methods.
Have fun,
Travis
Yesterday, I encountered an interesting side-effect of iterators. Even
though the code looked fine, it actually was completely wrong. See if
you can figure out why this code doesn't do as it is expected and how
to fix it:
// Returns indicies of matching items
public static IEnumerable<int> FindAll(IList<T> list, Predicate<T>
predicate)
{
for (int i = 0; i != list.Count; ++i)
{
if (predicate(list))
{
yield return i;
}
}
}
// Removes the items in the IList at the given indicies (if it's not
an T[])
public static void RemoveAt(IList<T> list, IEnumerable<int> indicies)
{
int shift = 0;
foreach (int index in indicies)
{
list.RemoveAt(index - shift);
++shift;
}
}
// Caller
List<int> values = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8,
9 });
IEnumerable<int> indicies = FindAll<int>(values, delegate (int
current) { return i % 2 == 0; });
RemoveAt(values, indicies);
I just forced the RemoveAt method to take the predicate, but there is
a way to fix the caller withouth touching the other methods.
Have fun,
Travis