Interesting Iterator Trivia - Thought I would share

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jehugaleahsa@gmail.com

    Interesting Iterator Trivia - Thought I would share

    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[i]))
    {
    yield return i;
    }
    }
    }

    // Removes the items in the IList at the given indicies (if it's not
    an T[])
    public static void RemoveAt(IList< Tlist, IEnumerable<int indicies)
    {
    int shift = 0;
    foreach (int index in indicies)
    {
    list.RemoveAt(i ndex - shift);
    ++shift;
    }
    }

    // Caller
    List<intvalues = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8,
    9 });
    IEnumerable<int indicies = FindAll<int>(va lues, 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
Working...