| Andrew Cooke | Contents | Latest | RSS | Twitter | Previous | Next


Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Lepl parser for Python.

Colorless Green.

Photography around Santiago.

SVG experiment.

Professional Portfolio

Calibration of seismometers.

Data access via web services.

Cache rewrite.

Extending OpenSSH.

C-ORM: docs, API.

Last 100 entries

Small Success With Go!; Re: Quick message - This link is broken; Adding Reverb To The Echo Chamber; Sox Audio Tools; Would This Have Been OK?; Honesty only important economically before institutions develop; Stegangraphy via PS4; OpenCL Mess; More Book Recommendations; Good Explanation of Difference Between Majority + Minority; Musical Chairs - Who's The Privileged White Guy; I can see straight men watching this conversation and laffing; When it's Actually a Source of Indignation and Disgust; Meta Thread Defending POC Causes POC To Close Account; Indigenous People Of Chile; Curry Recipe; Interesting Link On Marginality; A Nuclear Launch Ordered, 1962; More Book Recs (Better Person); It's Nuanced, And I Tried, So Back Off; Marx; The Negative Of Positive; Jenny Holzer Rocks; Huge Article on Cultural Evolution and More; "Ignoring language theory"; Negative Finger Counting; Week 12; Communication Via Telecomm Bids; Finding Suspects Via Relatives' DNA From Non-Crime Databases; Statistics and Information Theory; Ice OK in USA; On The Other Hand; (Current Understanding Of) Chilean Taxes / Contributions; M John Harrison; Playing Games on a Cloud GPU; China Gamifies Real Life; Can't Help Thinking It's Thoughtcrime; Mefi Quotes; Spray Painting Bike Frame; Weeks 10 + 11; Change: No Longer Possible To Merge Metadata; Books on Old Age; Health Tree Maps; MRA - Men's Rights Activists; Writing Good C++14; Risk Assessment - Fukushima; The Future of Advertising and Surveillance; Travelling With Betaferon; I think I know what I dislike so much about Metafilter; Weeks 8 + 9; More; Pastamore - Bad Italian in Vitacura; History Books; Iraq + The (UK) Governing Elite; Answering Some Hard Questions; Pinochet: The Dictator's Shadow; An Outsider's Guide To Julia Packages; Nobody gives a shit; Lepton Decay Irregularity; An Easier Way; Julia's BinDeps (aka How To Install Cairo); Good Example Of Good Police Work (And Anonymity Being Hard); Best Santiago Burgers; Also; Michael Emmerich (Vibrator Translator) Interview (Japanese Books); Clarice Lispector (Brazillian Writer); Books On Evolution; Looks like Ara (Modular Phone) is dead; Index - Translations From Chile; More Emotion in Chilean Wines; Week 7; Aeon Magazine (Science-ish); QM, Deutsch, Constructor Theory; Interesting Talk Transcripts; Interesting Suggestion Of Election Fraud; "Hard" Books; Articles or Papers on depolarizing the US; Textbook for "QM as complex probabilities"; SFO Get Libor Trader (14 years); Why Are There Still So Many Jobs?; Navier Stokes Incomplete; More on Benford; FBI Claimed Vandalism; Architectural Tessellation; Also: Go, Blake's 7; Delusions of Gender (book); Crypto AG DID work with NSA / GCHQ; UNUMS (Universal Number Format); MOOCs (Massive Open Online Courses); Interesting Looking Game; Euler's Theorem for Polynomials; Weeks 3-6; Reddit Comment; Differential Cryptanalysis For Dummies; Japanese Graphic Design; Books To Be Re-Read; And Today I Learned Bugs Need Clear Examples; Factoring a 67 bit prime in your head; Islamic Geometric Art; Useful Julia Backtraces from Tasks; Nothing, however, is lost with less discomfort than that which, when lost, cannot be missed

© 2006-2015 Andrew Cooke (site) / post authors (content).

Example Clojure Code

From: andrew cooke <andrew@...>

Date: Sun, 14 Aug 2011 19:25:04 -0400

With the disclaimer that I am still new to all this, here is a fragment of
Clojure code along with some commentary.  The idea is to take some "typical"
code from the project I am working on and show the aspects of Clojure that
I've found interesting so far.

Code is indented a couple of spaces; commentary is left-justified.

First, some records.  These are just collections of named values (maps,
basically).  One of the recurring themes in Clojure is that it relies on
re-use of simple interfaces that are common to many different data structures
- although each record here is a different type they are typically accessed
in the same way as a general map.

  (defrecord linear-sampling [t0 dt n])
  (defrecord signal [xyz sampling data])

The "signal" record consists of an [x y z] vector, an instance of
"linear-sampling" that describes the time range (and sampling period) of the
data, and a vector of values (size n, for times t0, t0+dt, etc).  The
duplication of size ("n" in "sampling", and the length of "data") isn't ideal,
but I need to specify samplings separately from signals in various places.

Next, the function itself.  The package as a whole is used to construct
synthetic waveform data.  This routine combines waveforms which may overlap,
adding them, and zero-padding to fill the entire range of values given by

This is bundled with some unit tests - they come after the function


    (defn combine-signals [sampling signals]
      "combine multiple signals to the new sampling: resampling with nearest 
       value as needed, adding overlapping data, and padding with zeros"

Here I'm extracting the "n" parameter from "sampling".  As I said above, this
could be any map with such a key (although in practice it's always a
"linear-sampling" instance).

      (let [n (:n sampling)

Next, a sequence of times.  This is Clojure's list comprehension syntax.  It
defines the times for the output data and is iterated over repeatedly below

	    times (for [i (range n)] (+ (:t0 sampling) (* (:dt sampling) i)))

And the meat of the routine: a recursive function that expands the signals one
by one, accumulating them in "results", which is initialised as a sequence of
zero pairs (the pairs are number of contributing waveforms and total value).

	    merge (fn [signals]

Clojure doesn't have automatic TCO (blame the JVM), but the "loop" construct
(together with "recur") will add it automatically.  "Loop" also allows for
initialisation of variables (here "result").

		    (loop [signals signals
			   result (repeat n [0 0])]

The base case: if no more input, return the result.

			(empty? signals) result

And the incremental case, which consumes one signal.

			(let [signal (first signals)
			      data (:data signal)

This is an interesting piece of destructuring/binding that extracts all the
values from the "sampling" record that is part of "signal".

			      {tstart :t0, dts :dt, ns :n} (:sampling signal)
			      tend (+ tstart (* ns dts))

A helper function that checks whether we are inside the time range for signal
and, if so, updates the result.

			      sum (fn [[count value] t]
				    (if (and (>= t tstart) (< t tend))
				      [(+ 1 count) (+ value (nth data (/ (- t tstart) dts)))]
				      [count value]))]

This maps "sum" above over the previous result and the times, and then
recurses/loops with one signal less.

			  (recur (rest signals) (map sum result times))))))

Finally, we normalize the result (this is why we were carrying around the
count of number of contributing waveforms per time step) and construct the
result record (another signal).

In case it's not obvious, Clojure uses "first"/"rest" rather than
"head"/"tail" or "car"/"cdr" (but these are more general functions - intended
for any sequence, including the 'standard' lazy sequences).

Again, note the destructureing below - I am unpacking the "count", "value"

	    data (vec (for [[count value] (merge signals)] (if (= count 0) 0 (/ value count))))]
	(signal. (:xyz (first signals)) sampling data)))

And here come the tests!  The first signal has value 1 for 2 bins starting at
0.3; the second has value 2 for 3 bins starting at 0.4.  So they overlap in
one bin and the final result is padded over the entire sampling range.

    (let [s (linear-sampling. 0 0.1 10)
	  c1 (constant-signal [5 6 7] (linear-sampling. 0.3 0.1 2) 1)
	  c2 (constant-signal [5 6 7] (linear-sampling. 0.4 0.1 3) 2)
	  b (combine-signals s [c1 c2])]

Print and assert values.

      (prn c1)
      (is (= '[1 1] (:data c1)))
      (prn c2)
      (is (= '[2 2 2] (:data c2)))
      (prn b)
      (is (= '[0 0 0 1 3/2 2 2 0 0 0] (:data b)))))

Note how the code combines vectors (constructed with "vec", or anything in
square brackets) and lazy sequences quite naturally.  I should also add that
it's OK (I think) for the algorithm above to be O(nxm) - it simplifies the
logic and is only used for generating test data, not for final processing.

My impression is that idiomatic Clojure should use vectors, [...], for small
tuples (as well as arrays of numeric data), and sequences for data flow within

Most of the sequences above (those generated with "for" and "map") are lazy -
I guess things are resolved by the final "vec".  Also, since they cache, the
repeated iteration over "times" will be efficient.

You might have noticed that records are constructed with a trailing dot.  I
*think* this may be a dotted cons.  Whatever it is, if you miss the "."  then
you get the most unhelpful error message (Java class cast exception).

While writing the above I tried to make a note of issues with Intellij's
plugin (La Clojure).  People on the HN thread were saying how good it is -
either have something messed up in configuration, or they have never used
Intellij with Java or Python.  It doesn't do basic things like flag unused
variables, often ignores recently defined functions during auto-complete, and
only reluctantly displays information on function signatures.  Some of this
may be because there is less syntax to rely on for semantic cues, but it could
at least recognise the core library...


Comment on this post