Why I love Clojure

Here’s some code I’m writing for my day-job.

I have an iterator of IScoreObjects (basically things that live on a musical score or timeline).

I want an iterator of only the Notes. Where Notes are one of the things that implement the IScoreObject interface and can live on the score.

Here’s my code.

import java.util.Iterator;

public class NoteIterator implements Iterator {
    /**
     * Takes an iterator of IScoreObjects and returns an Iterator of only the Notes
     */
    Iterator isoIterator;
    Note _next;
    boolean _hasNext;

    public NoteIterator(Iterator isoi) {
        isoIterator = isoi;
        findNext();
    }

    private void findNext() {
        while (isoIterator.hasNext()) {
            IScoreObject n = isoIterator.next();
            if (n.isNote()) {
                _next = (Note)n;
                _hasNext = true;
                return;
            }
        }
        _next = null;
        _hasNext = false;
    }

    @Override
    public boolean hasNext() {
        return _hasNext;
    }

    @Override
    public Note next() {
        Note rv = _next;
        findNext();
        return rv;
    }
}

On the other hand, here’s how I’d do it in Clojure

(defn just-the-notes [score-objects] (filter .isNote score-objects))

This is literally something like a 20:1 ratio in line count. And the Java needs an extra file of its own. That is insane.

Leave a comment