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

C-ORM: docs, API.

Last 100 entries

Alternative Japanese Lit; Pulic Key as Address (Snow); Why Information Grows; The Blindness Of The Chilean Elite; Some Victoriagate Links; This Is Why I Left StackOverflow; New TLS Implementation; Maths for Physicists; How I Am 8; 1000 Word Philosophy; Cyberpunk Reading List; Detailed Discussion of Message Dispatch in ParserCombinator Library for Julia; FizzBuzz in Julia w Dependent Types; kokko - Design Shop in Osaka; Summary of Greece, Currently; LLVM and GPUs; See Also; Schoolgirl Groyps (Maths); Japanese Lit; Another Example - Modular Arithmetic; Music from United; Python 2 and 3 compatible alternative.; Read Agatha Christie for the Plot; A Constructive Look at TempleOS; Music Thread w Many Recommendations; Fixed Version; A Useful Julia Macro To Define Equality And Hash; k3b cdrom access, OpenSuse 13.1; Week 2; From outside, the UK looks less than stellar; Huge Fonts in VirtualBox; Keen - Complex Emergencies; The Fallen of World War II; Some Spanish Fiction; Calling C From Fortran 95; Bjork DJ Set; Z3 Example With Python; Week 1; Useful Guide To Starting With IJulia; UK Election + Media; Review: Reinventing Organizations; Inline Assembly With Julia / LLVM; Against the definition of types; Dumb Crypto Paper; The Search For Quasi-Periodicity...; Is There An Alternative To Processing?; CARDIAC (CARDboard Illustrative Aid to Computation); The Bolivian Case Against Chile At The Hague; Clear, Cogent Economic Arguments For Immigration; A Program To Say If I Am Working; Decent Cards For Ill People; New Photo; Luksic And Barrick Gold; President Bachelet's Speech; Baltimore Primer; libxml2 Parsing Stream; configure.ac Recipe For Library Path; The Davalos Affair For Idiots; Not The Onion: Google Fireside Chat w Kissinger; Bicycle Wheels, Inertia, and Energy; Another Tax Fraud; Google's Borg; A Verion That Redirects To Local HTTP Server; Spanish Accents For Idiots; Aluminium Cans; Advice on Spray Painting; Female View of Online Chat From a Male; UX Reading List; S4 Subgroups - Geometric Interpretation; Fucking Email; The SQM Affair For Idiots; Using Kolmogorov Complexity; Oblique Strategies in bash; Curses Tools; Markov Chain Monte Carlo Without all the Bullshit; Email Para Matias Godoy Mercado; The Penta Affair For Idiots; Example Code To Create numpy Array in C; Good Article on Bias in Graphic Design (NYTimes); Do You Backup github?; Data Mining Books; SimpleDateFormat should be synchronized; British Words; Chinese Govt Intercepts External Web To DDOS github; Numbering Permutations; Teenage Engineering - Low Price Synths; GCHQ Can Do Whatever It Wants; Dublinesque; A Cryptographic SAT Solver; Security Challenges; Word Lists for Crosswords; 3D Printing and Speaker Design; Searchable Snowden Archive; XCode Backdoored; Derived Apps Have Malware (CIA); Rowhammer - Hacking Software Via Hardware (DRAM) Bugs; Immutable SQL Database (Kinda); Tor GPS Tracker; That PyCon Dongle Mess...; ASCII Fluid Dynamics; Brandalism; Table of Shifter, Cassette and Derailleur Compatability

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