On Thu, Mar 10, 2011 at 12:46 PM, Damien Lepage <damienlep...@gmail.com> wrote: > Hi > > I wrote a function to transform a variable number of arguments into embedded > maps. > Here is what it does: >> (enmap 1 2) > {1 2} >> (enmap 1 2 3) > {1 {2 3}} >> (enmap 1 2 3 4) > {1 {2 {3 4}}} >> (enmap 1 2 3 4 {5 6 7 8}) > {1 {2 {3 {4 {5 6, 7 8}}}}} > Here is my implementation: > (defn enmap [arg & args] > (if-let [more (butlast args)] > (let [k (last more), v (last args)] > (if-let [even-more (butlast more)] > (apply enmap arg (concat even-more (list (hash-map k v)))) > (enmap arg (hash-map k v)))) > (apply hash-map arg args))) > Two things bother me: > > Is there a way to make this function less complicated? without recursion > maybe? > Is there something simpler than (concat even-more (list (hash-map k v)) to > append an element at the end of a sequence? >
When I see a pattern like this of repeatedly doing something to a collection, I immediately think of "reduce". For fun, let's see what happens when I try it: user=> (reduce hash-map [1 2 3 4 5]) {{{{1 2} 3} 4} 5} Close, but backwards. I know reduce is equivalent to a left-fold, so to get the opposite I want a right-fold. Clojure doesn't have that built-in, but one way to define it: user=>(defn foldr [f coll] (reduce #(f %2 %1) (reverse coll))) Now, we can: user=>(foldr hash-map [1 2 3 4 5]) {1 {2 {3 {4 5}}}} -- 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