On Wed, Aug 27, 2008 at 12:11 AM, Chouser <[EMAIL PROTECTED]> wrote: > > > You could simplify your reduce fn a bit by using merge-with: > Or even: > > (defn test-shuffle-uniformity > "Shuffles a 3-item collection n times, mapping each result to the number > of > times it's hit. If the distribution isn't uniform we've let bias into the > random numbers or the algorithm. Typical results on my machine: > (2 1 3) : 16611 > (3 2 1) : 16771 > (1 3 2) : 16707 > (1 2 3) : 16766 > (3 1 2) : 16555 > (2 3 1) : 16590" > ([n] (test-shuffle-uniformity n shuffle)) > ([n shuffle] > (let [coll [1 2 3] > results (apply merge-with + {} > (take n (repeatedly (fn [] {(shuffle coll) 1}))))] > (doseq [k v] results > (println k ":" v))))) >
Interesting suggestion. I think reduce expresses my intent a little better, but I need to keep merge-with in mind for other uses. > It'd be nice to use the #(...) syntax instead of (fn [] ...), but that > won't work here since #({key val}) would try to call the map with no > arguments. You'd have to say #(hash-map key val) and (fn [] {key > val}) is arguably clearer. > Heh, having #( ) available gives me a concision addiction. I'm trying to heed the advice of the docs not to replace fn everywhere, but it's always tempting to use. I definitely tried to write #(rand) in shuffle, but ran into the same no-arguments problem. Also note the destructuring in doseq to save a few keystrokes. > Ah, I didn't realize at the time that doseq supported destructuring, but that rocks. > Or you can rely on the fact that vectors are comparable themselves. > The first member is the most significant, so I'd think this would > produce acceptable results. It's more succinct and appears to double > the speed: > > (defn sort-by-mem-keys > "Like clojure/sort-by but only calls keyfn once on each item in coll." > ([keyfn coll] > (let [key-vals (map (fn [x] [(keyfn x) x]) coll)] > (map second (sort key-vals))))) > That's very clean. When duplicate keys arise that implementation is probably has similar behavior to the original, assuming the values in coll are Comparable. Either way, I haven't tested mine for uniformity with large inputs, and given the superiority of the Java solution, I'm done. Thanks for the pointers! Shawn --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---