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

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.

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.

Last 100 entries

The Quest for Randomness; Chat Wars; Real-life Financial Co Without ACID Database...; Flexible Muscle-Based Locomotion for Bipedal Creatures; SQL Performance Explained; The Little Manual of API Design; Multiple Word Sizes; CRC - Next Steps; FizzBuzz; Update on CRCs; Decent Links / Discussion Community; Automated Reasoning About LLVM Optimizations and Undefined Behavior; A Painless Guide To CRC Error Detection Algorithms; Tests in Julia; Dave Eggers: what's so funny about peace, love and Starship?; Cello - High Level C Programming; autoreconf needs tar; Will Self Goes To Heathrow; Top 5 BioInformatics Papers; Vasovagal Response; Good Food in Vina; Chilean Drug Criminals Use Subsitution Cipher; Adrenaline; Stiglitz on the Impact of Technology; Why Not; How I Am 5; Lenovo X240 OpenSuse 13.1; NSA and GCHQ - Psychological Trolls; Finite Fields in Julia (Defining Your Own Number Type); Julian Assange; Starting Qemu on OpenSuse; Noisy GAs/TMs; Venezuela; Reinstalling GRUB with EFI; Instructions For Disabling KDE Indexing; Evolving Speakers; Changing Salt Size in Simple Crypt 3.0.0; Logarithmic Map (Moved); More Info; Words Found in Voynich Manuscript; An Inventory Of 3D Space-Filling Curves; Foxes Using Magnetic Fields To Hunt; 5 Rounds RC5 No Rotation; JP Morgan and Madoff; Ori - Secure, Distributed File System; Physical Unclonable Functions (PUFs); Prejudice on Reddit; Recursion OK; Optimizing Julia Code; Cash Handouts in Brazil; Couple Nice Music Videos; It Also Works!; Adaptive Plaintext; It Works!; RC5 Without Rotation (2); 8 Years...; Attack Against Encrypted Linux Disks; Pushing Back On NSA At IETF; Summary of Experimental Ethics; Very Good Talk On Security, Snowden; Locusts are Grasshoppers!; Vagrant (OpenSuse and IDEs); Interesting Take On Mandela's Context; Haskell Cabal O(n^2) / O(n) Fix; How I Am 4; Chilean Charity Supporting Women; Doing SSH right; Festival of Urban Intervention; Neat Idea - Wormholes Provide Entanglement; And a Link....; Simple Encryption for Python 2.7; OpenSuse 13.1 Is Better!; Little Gain...; More Details on Technofull Damage; Palmrest Cracked Too....; Tecnofull (Lenovo Support) Is Fucking Useless; The Neuroscientist Who Discovered He Was a Psychopath; Interpolating Polynomials; Bottlehead Crack as Pre-amp; Ooops K702!; Bottlehead Crack, AKG K701; Breaking RC5 Without Rotation; Great post thank you; Big Balls of Mud; Phabricator - Tools for working together; Amazing Julia RC5 Code Parameterized By Word Size; Chi-Square Can Be Two-Sided; Why Do Brits Accept Surveillance?; Statistics Done Wrong; Mesas Trape from Bravo; European Report on Crypto Primitives and Protocols; Interesting Omissions; Oryx And Crake (Margaret Atwood); Music and Theory; My Arduino Programs; Elliptic Curve Crypto; Re: Licensing Interpreted Code; Licensing Interpreted Code; ASUS 1015E-DS03 OpenSuse 12.3 SSD; translating lettuce feature files into stub steps files; Re: translating lettuce feature files into stub steps files

© 2006-2013 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 
       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.

		      (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

Comment on this post