Skip to content

Instantly share code, notes, and snippets.

@tomjack
Created April 7, 2010 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomjack/bf8f747e4ffa29591665 to your computer and use it in GitHub Desktop.
Save tomjack/bf8f747e4ffa29591665 to your computer and use it in GitHub Desktop.
(ns scratch.mapcat
(:use [clojure.set :only (union)]))
(defn divisors [n]
(filter (comp zero? (partial mod n))
(range 2 n)))
(defn mapcat2 [f & colls]
(reduce concat (apply map f colls)))
(defn reduce-vs-apply []
(println "apply:")
(time (dorun (mapcat divisors (range 1000))))
(println "reduce:")
(time (dorun (mapcat2 divisors (range 1000)))))
;; apply:
;; "Elapsed time: 1723.707991 msecs"
;; reduce:
;; "Elapsed time: 6491.475802 msecs"
;; (defn mapunion [f & colls]
;; (reduce into (cons #{} (apply map f colls))))
(defn mapunion [f & colls]
(->> (apply map f colls)
(cons (transient #{}))
(reduce (partial reduce conj!))
persistent!))
(defn mapcat-vs-mapunion []
(println "mapcat:")
(time (dorun (mapcat divisors (range 2000))))
(println "mapunion:")
(time (dorun (mapunion divisors (range 2000)))))
;; mapcat:
;; "Elapsed time: 6523.554967 msecs"
;; mapunion:
;; "Elapsed time: 6505.352707 msecs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment