if i was writing the java i would probably do a "tell dont ask"
refactoring so that the operations had an applyTo method:

List<Item> items = initialItems ();

for (Op op : operations)
{
  op.applyTo(items);
}

not sure what your op data structure is, but i would image you could
translate that to the clojure code also -- is that reasonable?


On Mon, Jun 13, 2011 at 9:37 PM, Matthew Phillips <mattp...@gmail.com> wrote:
> 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 clojure@googlegroups.com
> Note that posts from new members are moderated - please be patient with your 
> first post.
> To unsubscribe from this group, send email to
> clojure+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to