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

Producer consumer with qualifications

Here’s my take on it. I made a point of only using Clojure data structures to see how that would work out. Note that it would have been perfectly usual and idiomatic to take a blocking queue from the Java toolbox and use it here; the code would be easy to adapt, I think. Update: … Read more

How to list the functions of a namespace?

I normally call (keys (ns-publics ‘foo)) to list Vars exported by the namespace foo; e.g. for clojure.contrib.monads this returns (defmonad censor m-when-not m+write+m maybe-m maybe-t …) (the … stands for quite a lot more). More generally, there’s a bunch of functions whose names start in ns- which list Vars by namespace, with certain additional criteria … Read more

What do Clojure symbols do when used as functions?

Symbols look themselves up in a map, much as keywords do. See Symbol’s implementation: … 122 public Object invoke(Object obj) { 123 return RT.get(obj, this); 124 } 125 126 public Object invoke(Object obj, Object notFound) { 127 return RT.get(obj, this, notFound); 128 } … (RT is clojure.lang.RT, which does just about everything. “RunTime”?) In the … Read more

How do I find the index of an item in a vector?

Built-in: user> (def v [“one” “two” “three” “two”]) #’user/v user> (.indexOf v “two”) 1 user> (.indexOf v “foo”) -1 If you want a lazy seq of the indices for all matches: user> (map-indexed vector v) ([0 “one”] [1 “two”] [2 “three”] [3 “two”]) user> (filter #(= “two” (second %)) *1) ([1 “two”] [3 “two”]) user> … Read more

difference between use and require

require loads libs (that aren’t already loaded), use does the same plus it refers to their namespaces with clojure.core/refer (so you also get the possibility of using :exclude etc like with clojure.core/refer). Both are recommended for use in ns rather than directly.