Clojure's combination of declarative idioms and highly functional idioms (to a greater extent than CL) lead to it being able to by default express certain things in a more terse fashion.
http://rosettacode.org/wiki/Factors_of_an_integer
Compare Common Lisp and Clojure here.
Common Lisp:
(defun factors (n &aux (lows '()) (highs '()))
(do ((limit (isqrt n)) (factor 1 (1+ factor)))
((= factor limit)
(when (= n (* limit limit))
(push limit highs))
(nreconc lows highs))
(multiple-value-bind (quotient remainder) (floor n factor)
(when (zerop remainder)
(push factor lows)
(push quotient highs)))))
Common Lisp in this case is relying heavily on mutation with push. It's not that much better than a typical loop in an iterative language like Python.Clojure solutions:
; Trivial version
(defn factors [n]
(filter #(zero? (rem n %)) (range 1 (inc n))))
Initial version just does a filter and a lambda across the sequence produced by range. inc so that it includes the final result. Pretty functional. ; Less trivial
(defn factors [n]
(into (sorted-set)
(mapcat (fn [x] [x (/ n x)])
(filter #(zero? (rem n %)) (range 1 (inc (sqrt n)))) )))
Now we're getting a little more clever, relying on mapcat, filter, a lambda, and range. ; Now with a for-comprehension.
(defn factors [n]
(into (sorted-set)
(reduce concat
(for [x (range 1 (inc (sqrt n))) :when (zero? (rem n x))]
[x (/ n x)]))))
http://clojure.github.com/clojure/clojure.core-api.html#cloj...Take a look at the other things that work across the seq'able data structures. Pretty powerful base set of idioms.
Okay, but lets provide a second opinion on these idioms. What about Haskell?
import HFM.Primes(primePowerFactors)
import Data.List
factors = map product.
mapM (uncurry((. enumFromTo 0) . map .(^) )) . primePowerFactors
Using a primes module for finding prime factors. Okay, isn't that kinda cheating Rosetta Code though? I was kinda hoping to find the equivalent of the Clojure code.And Mathematica?
Factorize[n_Integer] := Divisors[n]
FFS.I give up. These are dumb comparisons. Don't listen to this Wolfram post. At least the Common Lisp/Clojure code wasn't pointless.