Hello all, I've been programming Clojure now for long enough that I'm
starting to think I'm at the point of being fluent … almost.
One area that keeps tripping me up is iteratively processing a data
structure when the processing is highly conditional and may take
several overlapping paths. An example might help:
Example (simplified from my current real problem): Say I need to
iterate through a seq of encoded list operations and apply them to a
list. Some ops will require me to remove an element from the list,
some will require me to add an item to list, and some will require
both. The way I'd write it in Java would be something like:
List<Item> items = initialItems ();
for (Op op : operations)
{
if (op.requiresDelete ())
items.remove (op.indexToDelete ());
if (op.requiresAdd ())
items.add (op.indexToAdd (), op.newItem ());
}
You could imagine arbitrarily complex conditions for the transforms.
The only way I can think of to write it in Clojure is:
(reduce
(fn [items op]
(let [items1 (if (:delete op) (drop-index (:delete op) items)
items)]
(if (:insert op) (cons (:insert op) items1) items1)))
items ops)
i.e. I'm using a cascade of conditional let's. This isn't _too_ bad in
this case, but you can image how unreadable this could get.
I have a vague idea that in Haskell you might use the ST monad to
approximate updating data structure "in place". Clojure has a monad
library, so would this make sense here?
Thanks for any enlightenment anyone is able to give.
Matthew.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en