Clojure multimethods vs. protocols

Protocol and multimethods are complementary and intended for slightly different use cases. Protocols provide efficient polymorphic dispatch based on the type of the first argument. Because the is able to exploit some very efficient JVM features, protocols give you the best performance. Multimethods enable very flexible polymorphism which can dispatch based on any function of … Read more

What are common conventions for using namespaces in Clojure?

I guess it’s ok if you think it helps, but many Clojure projects don’t do so — cf. Compojure (using a top-level compojure ns and various compojure.* ns’s for specific functionality), Ring, Leiningen… Clojure itself uses clojure.* (and clojure.contrib.* for contrib libraries), but that’s a special case, I suppose. Yes! You absolutely must do so, … Read more

How many primitives does it take to build a LISP machine? Ten, seven or five?

Basic Predicates/F-functions McCarthy‘s Elementary S-functions and Predicates were: atom Which was necessary because car and cdr are defined for lists only, which means you cannot count on any sort of answer to indicate what was happening if you gave car an atom. eq For testing equality between atoms. car For returning the first half (address) … Read more

clojure.java.jdbc lazy query

First, see https://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor. Solved it like this. (jdbc/with-db-transaction [tx connection] (jdbc/query tx [(jdbc/prepare-statement (:connection tx) “select * from mytable” {:fetch-size 10})] {:result-set-fn (fn [result-set] …)})) where :result-set-fn is a function that consumes the lazy result set. with-db-transaction takes care of autoCommit set to false. :fetch-size is not passed from query so you have to make … Read more

Fast Prime Number Generation in Clojure

Here’s another approach that celebrates Clojure’s Java interop. This takes 374ms on a 2.4 Ghz Core 2 Duo (running single-threaded). I let the efficient Miller-Rabin implementation in Java’s BigInteger#isProbablePrime deal with the primality check. (def certainty 5) (defn prime? [n] (.isProbablePrime (BigInteger/valueOf n) certainty)) (concat [2] (take 10001 (filter prime? (take-nth 2 (range 1 Integer/MAX_VALUE))))) … Read more