DEV Community

Discussion on: Types of Loops

Collapse
 
louy2 profile image
Yufan Lou

Looks like you are teaching in Java. Java has iterator for loop syntax too, called for-each loop:

for (var hay : haystack) {}

Another point Haskell has revealed to me is that we don't need the concept of index to describe operations on a list. You mentioned the linked list loop as a "more advanced loop", but I think that might be the easier one, if we remove the ++i. It's a loop after all, so if you describe it as "we start from the beginning, process the next item, until we have nothing left," then it matches the language better than the index version. It's just convention that we introduce array before linked list, but that's from a implementer's perspective. I think from a user's perspective, a list interface, or in Java, the Iterator interface, is easier to learn because there's less to keep in mind. I don't think "iterate" the word itself is confusing your students, but rather the fact that they are learning "for loop" along with "iterate", and that the word "iterate" never appeared in the code.

A rewrite of your three loops with the Iterator interface:

Find loop

Because this accesses index it has to use listIterator(). I don't like Java.

public static int indexOf(List<String> haystack, String needle) {
    for (Iterator it = haystack.listIterator(); it.hasNext(); ) {
        if (needle.equals(it.next())) {
            return it.previousIndex();
        }
    }
}

Count loop

You know what, let's just use listIterator() throughout. One less thing to care about.

public static int countOf(List<String> haystack, String needle) {
    int count = 0;
    for (Iterator it = haystack.listIterator(); it.hasNext(); ) {
        if (needle.equals(it.next())) {
            count++;
        }
    }

    return count;
}

Action loop

public static void printAll(List<String> haystack) {
    for (Iterator it = haystack.listIterator(); it.hasNext(); ) {
        System.out.println(it.next());
    }
}