How do I map with rarely used state in clojure?

Viewed 176

The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}

However in Clojure the best I've come up with is:

(first 
 (reduce 
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))

Which is pretty ugly considering that without the special case this would become:

(map #(cond 
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

5 Answers
Related