Difference between Symbols and Vars in Clojure

There’s a symbol + that you can talk about by quoting it: user=> ‘+ + user=> (class ‘+) clojure.lang.Symbol user=> (resolve ‘+) #’clojure.core/+ So it resolves to #’+, which is a Var: user=> (class #’+) clojure.lang.Var The Var references the function object: user=> (deref #’+) #<core$_PLUS_ clojure.core$_PLUS_@55a7b0bf> user=> @#’+ #<core$_PLUS_ clojure.core$_PLUS_@55a7b0bf> (The @ sign is … 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

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

How do I avoid Clojure’s chunking behavior for lazy seqs that I want to short circuit?

CORRECTED TWICE: A simpler way to un-chunk a lazy sequence: (defn unchunk [s] (when (seq s) (lazy-seq (cons (first s) (unchunk (next s)))))) First version omitted (when … so it returned an infinite seq of nil’s after the input sequence ended. Second version used first instead of seq so it stopped on nil. RE: your … 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.

Idiomatic clojure map lookup by keyword

(:color my-car) is fairly standard. There are a few reasons for this, and I won’t go into all of them. But here’s an example. Because :color is a constant, and my-car is not, hotspot can completely inline the dynamic dispatch of color.invoke(m), which it can’t do with m.invoke(color) (in some java pseudo-code). That gets even … Read more