Andrew Cooke | Contents | Latest | RSS | 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

Choochoo Training Diary

Last 100 entries

Surprise Paradox; [Books] Good Author List; [Computing] Efficient queries with grouping in Postgres; [Computing] Automatic Wake (Linux); [Computing] AWS CDK Aspects in Go; [Bike] Adidas Gravel Shoes; [Computing, Horror] Biological Chips; [Books] Weird Lit Recs; [Covid] Extended SIR Models; [Art] York-based Printmaker; [Physics] Quantum Transitions are not Instantaneous; [Computing] AI and Drum Machines; [Computing] Probabilities, Stopping Times, Martingales; bpftrace Intro Article; [Computing] Starlab Systems - Linux Laptops; [Computing] Extended Berkeley Packet Filter; [Green] Mainspring Linear Generator; Better Approach; Rummikub Solver; Chilean Poetry; Felicitations - Empowerment Grant; [Bike] Fixing Spyre Brakes (That Need Constant Adjustment); [Computing, Music] Raspberry Pi Media (Audio) Streamer; [Computing] Amazing Hack To Embed DSL In Python; [Bike] Ruta Del Condor (El Alfalfal); [Bike] Estimating Power On Climbs; [Computing] Applying Azure B2C Authentication To Function Apps; [Bike] Gearing On The Back Of An Envelope; [Computing] Okular and Postscript in OpenSuse; There's a fix!; [Computing] Fail2Ban on OpenSuse Leap 15.3 (NFTables); [Cycling, Computing] Power Calculation and Brakes; [Hardware, Computing] Amazing Pockit Computer; Bullying; How I Am - 3 Years Post Accident, 8+ Years With MS; [USA Politics] In America's Uncivil War Republicans Are The Aggressors; [Programming] Selenium and Python; Better Walking Data; [Bike] How Fast Before Walking More Efficient Than Cycling?; [COVID] Coronavirus And Cycling; [Programming] Docker on OpenSuse; Cadence v Speed; [Bike] Gearing For Real Cyclists; [Programming] React plotting - visx; [Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life

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