I too think this is interesting because because it serves to illustrate some important general aspects of Clojure with a very simple problem.

I wrote four Clojure programs contrasting different ways of solving the problem, and then timed the application of each ten times to a million-item sequence /mill-float-numbs/ of floating-point random numbers. Here are the interesting results:

(defn average1
  [seq1]
  (/ (reduce + seq1) (count seq1)))

(defn average2
  [seq1]
  (loop [remaining (rest seq1)
            cnt 1
            accum (first seq1)]
    (if (empty? remaining)
      (/ accum cnt)
      (recur (rest remaining)
                (inc cnt)
                (+ (first remaining) accum)))))

(defn average3
  [seq1]
  (letfn [(count-add
             [ [cnt accum] numb]
             [(inc cnt) (+ accum numb)] ) ]
    (let [result-couple (reduce count-add [0 0] seq1)]
      (/ (result-couple 1) (result-couple 0)))))

(defn average4
  [seq1]
    (let [result-couple (reduce
                                  (fn [ [cnt accum] numb]
                                    [(inc cnt) (+ accum numb)] )
                                  [0 0]
                                  seq1)]
      (/ (result-couple 1) (result-couple 0))))

user=> (time (dotimes [i 10] (average1 /mill-float-numbs/)))
"Elapsed time: 526.674 msecs"

user=> (time (dotimes [i 10] (average2 /mill-float-numbs/)))
"Elapsed time: 646.608 msecs"

user=> (time (dotimes [i 10] (average3 /mill-float-numbs/)))
"Elapsed time: 405.484 msecs"

user=> (time (dotimes [i 10] (average4 /mill-float-numbs/)))
"Elapsed time: 394.31 msecs"

  --Larry

On 3/30/12 1:31 AM, Benjamin Peter wrote:
I think this topic is interesting. My guess would be, that the
sequence would have been traversed completely by the reduce call and
therefore clojure could know it's size and provide a constant time
count.

Could this be implemented? Is it?

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