# C[omp]ute

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.

© 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
"sampling".

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

(with-test

(defn combine-signals [sampling signals]
"combine multiple signals to the new sampling: resampling with nearest

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.

(if
(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"
pair.

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
algorithms.

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...

Andrew