Hi all,

I am relatively new to clojure. I am trying to port some toy code I
wrote for common lisp a few years ago (a boggle-like game which needs
a dictionary prefix trie to trim possible word matches).

My old code was fairly imperative in nature when creating the
dictionary trie, and so now I am having fun exercising my brain trying
to do the "right thing" with functional programming.

One thing I immediately ran up against were certain situations where I
have a map and want to "modify" a value several levels deep into the
hierarchy.  Imagine the following structure:

(def nested-structure { :level 0,
                             :nested1 { :level 1,
                                       :nested2 { :level 2,
                                                 :final-data "initial data"}}})

If I need to change the value for :final-data,  the chain of nested
"assoc", and  "get" becomes unwieldy (IMO).  So I spent several hours
scanning through the API to see what might help me out in this.  I
thought that the (->) macro was where it was at, but spun my wheels.
I thought potentially, that the destructuring capabilities of "let"
would help me out, but again I could not get anything to work the way
I wanted...  I played around with various "reduce" concoctions
(accumulating closures) and even toyed with generating a macro, before
I realized how easy it was:

;; keys is a vector of steps in a path, navigating down a map
hierarchy
(defn path-rebind [map keys val]
  (let [ [first & rest] keys
         nested-val (get map first) ]
    (if rest
      (assoc map first (path-rebind nested-val rest val))
      (assoc map first val))))

user> (path-rebind nested-structure [:nested1 :nested2 :final-data]
"new data")
{:nested1 {:nested2 {:final-data "new data", :level 2}, :level
1}, :level 0}

So, I have two questions:

1) Am I missing something from the API that could have done what my
function "path-rebind"? (I would have assumed that this would be a
common need and that programmers would not need to roll their own each
time)
2) Am I missing out on a clever "reduce" usage that could have made
this more in-line?  i.e. how's my code?

It was after I made wrote this function and contemplated how I could
make it abstract (i.e. with vectors, lists, etc) that I noticed the
existence of the "zip" library...  Maybe question 1) above is answered
by the "zip" library.  Is/Will the zip library be the recommended
means by which to navigate/modify data structures of arbitrary depth,
branching, and concrete 'type' ?


daniel



--~--~---------~--~----~------------~-------~--~----~
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
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to