I've been writing Clojure code today and have noticed the same pattern
show up multiple times, but can't find an elegant way to code it in
idiomatic Clojure. I feel like I'm missing an obvious solution...
anyone else see something I don't? Thanks in advance!

The problem boils down to the following minimal example: Suppose you
want to write a function "left-total" which takes a list of number and
returns pairs of said numbers, along with the total of numbers to the
left:

=> (left-total [3 5 10 1 2 7])
([3 0] [5 3] [10 8] [1 18] [2 19] [7 21])

I can think of several ways to write this function. Three acceptable
versions of this function are written below, but all of them are
hideous looking. Is there a better solution? (Note that any solution
should avoid thrashing the stack or performing more than the minimum
number of additions.)

(defn left-total [lst]
  (loop [lst lst
         acc nil
         tot 0]
    (if (seq lst)
      (let [[cur & more] lst]
        (recur more (cons [cur tot] acc) (+ tot cur)))
      (reverse acc))))

(defn left-total [lst]
  (reverse (first (reduce (fn [[acc tot] cur]
                            [(cons [cur tot] acc) (+ tot cur)])
                          [nil 0]
                          lst))))

(defn left-total [lst]
  (let [tot (atom 0)]
    (map (fn [cur]
           (let [old-tot @tot]
             (swap! tot (partial + cur))
             [cur old-tot]))
         lst)))


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