Clojure Weekly, Nov 25th, 2015

And here we go with another issue of Clojure Weekly! Clojure Weekly is a collection of bookmarks, normally 4/5, pointing at articles, docs, screencasts, podcasts and anything else that attracts my attention in the clojure-sphere for the last 7 (or so) days. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

Debugging with the Scientific Method - Stuart Halloway - YouTube Conj videos are already available (gone are the time you had to wait months for talks!). Debugging is a subject that we kind of give for granted. When you go deeper into the reasons behind it, the correct terminology and process there is still a lot to learn. Stuart gives an entertaining talk here despite the serious subject. There is a lot of common sense on what is said here about a scientific method, despite that the same old debugging mistakes are repeated over and over again. Remember: it’s always the garbage collector.

Condition Systems in an Exceptional Language - Chris Houser - YouTube Out of the very good selection at the Conj let me pick this great talk by Chris Houser (core committer, Joy of Clojure co-author and many other stuff). This talk is about condition systems, something already available in Lisp that is present with a few libraries for Clojure. A condition system is a flexible way to handle exceptions, giving clients a way to hookup into the exception propagation mechanism itself. The examples are inspired by chapter 19 from Practical Common Lisp book and the talk is anyway very rich in good references.

Clojure Destructuring Tutorial and Cheat Sheet A quick destructuring cheat-sheet with all the necessary pieces for effective splitting apart of your Clojure data structures. Worth remembering a couple of things: especially during interop scenarios map keys can come back as strings instead of keys. There is a : strs for that. Second: although a little bit evil, destructuring can be nested (map inside a vector inside a map and so on) with drastic reduction of lines of code.

Colin Fleming - Improving Clojure’s Error Messages with Grammars Another awesome talk from the Conj is this one by Colin Fleming of Cursive fame. The talk is great for many reasons: it touches on slowness of Clojure ticket process to fix also important problems, it shows all the possible ways to make mistakes on a (defn) declaration (wow, there are so many), a grammar to parse Clojure macros, how Cursive take advantage of that, the problem with error messages and Clojure adoption and all in a funny and entreating way. A final message: always look at the Scheme folks.

[#CLJ-1744] Unused destructured local not cleared, causes memory leak I was keeping an eye on some tweets and James Henderson added a real use case explaining how easily this problem can happen. I think I personally have tons of unused destructuring :as flying around and never payed too much attention to them. Just in case, if you are experiencing weird out of mem thinking you’re operating lazily on some big collection, double check all destructuring locals are being used


Clojure Libraries in The Matrix

Clojure universe is mostly built on top of libraries rather than “frameworks” or “platforms”, which makes it really flexible and lots of fun to work with. Any library can be swapped, contributed to, or even created from scratch. There are several things that make libraries great. The quality of its solution is of course the […]


Lesser known Clojure: keep, keep-indexed and map-indexed functions

I could safely say that map, reduce and filter are the most commonly used functions in Clojure (and probably other functional languages). Of course Clojure provides other useful functions that operate on collections that are not so popular and commonly known. Let’s look at some of them.


Let’s start with the keep function. Its idea is simple, it takes function f as a first parameter and a collection as second:

(keep f coll)

The result is a lazy sequence of results of applying f to every item in this collection - (f item). There is only one important condition, if result of (f item) gives nil then this item isn’t in returned sequence. On the other hand (in contrast to the filter function), if (f item) returns false it appears in result.

Let’s look at the example:

(keep :a '({:a 1} {:b 3} {:a 8} {:z 7}))
=> (1 8)

Here we use :a keyword as a function (it implements IFn interface) on collection of maps. The result is a sequence with 1 and 8, because (:a {:a 1}) evaluates to 1 and (:a {:a 8}) returns 8. The (:a {:b 3}) and (:a {:z 8}) evaluates to nil, so they aren’t in the final result.

For comparison if we use filter we get such result:

(filter :a '({:a 1} {:b 3} {:a 8} {:z 7}))
=> ({:a 1} {:a 8})

and map behaves in this way:

(map :a '({:a 1} {:b 3} {:a 8} {:z 7}))
=> (1 nil 8 nil)


We can say that keep-indexed is extended version of keep function. The difference is that the function f that we pass as a first argument must have such signature:

(fn [index item])

where index will get succeeding non-negative integers starting with 0:

 (fn [index item]
   [index (:a item)])
 '({:a 1} {:b 3} {:a 8} {:z 7}))

=> ([0 1] [1 nil] [2 8] [3 nil])

and one more example (that have more sense):

 (fn [index item]
   (when (even? index)
     (:a item)))
 '({:a 1} {:a 5} {:b 3} {:a 8} {:a 12} {:z 7}))

=> (1 12)

Here we want to return only values of keyword :a in the map if the map is on the even position (like: 0, 2, 4, 6 and so on) in the collection and has this keyword.


The map-indexed function is equivalent of keep-indexed function, but of course it behaves in the same way as map function. In another words, it transform a sequence of items to another sequence, by applying function f to every item in the original collection. The function f takes index as a first parameter and item as second:

 (fn [index item] [index item])
 '(:a :b :c :d :e :f))

=> ([0 :a] [1 :b] [2 :c] [3 :d] [4 :e] [5 :f])

This way we don’t need to use some kind of loop when we need to transform items in collection and we need to know the position of item in the sequence.

(side note: all those function has also version that produce transducer, but for simplicity I’ve skipped it)


November 2015 London Clojure Dojo at ThoughtWorks (Soho)

Tuesday, November 24, 2015 from 7:00 PM to 10:00 PM (GMT)

ThoughtWorks London Office
1st Floor
76-78 Wardour Street
W1F 0UR London
United Kingdom

Hosted By:
London Clojurians

Register for this event now at :

Event Details:

London Clojure Dojo at ThoughtWorks (Soho)

The goal of the session is to help people learn to start working with Clojure through practical exercises, but we hope that more experienced developers will also come along to help form a bit of a London Clojure community. The dojo is a great place for new and experienced clojure coders to learn more. If you want to know how to run your own dojo or get an idea of what dojos are like you can read more here.

We hope to break up into groups for the dojo. So if you have a laptop with a working clojure environment please bring it along.

We’ll be discussing the meetup on the london-clojurians mailing list

Clojure is a JVM language that has syntactically similarities to Lisp, full integration with Java and its libraries and focuses on providing a solution to the issue of single machine concurrency.

Its small core makes it surprisingly easy for Java developers to pick up and it provides a powerful set of concurrency strategies and data structures designed to make immutable data easy to work with. If you went to Rich Hickey’s LJC talk about creating Clojure you’ll already know this, if not it’s well worth watching the Rich Hickey “Clojure for Java Programmers” video or Stuart Halloway “Radical Simplicity” video.


Functional Geekery Episode 36 – Rob Sullivan (a.k.a DataChomp)

In this episode I talk with Rob Sullivan. We talk about his entry into and experience with functional programming from the perspective of a DBA, and how functional programming languages’ massive concurrency and speed change the constraints around the database.

Our Guest, Rob Sullivan

Rob is @datachomp on Twitter


This episode is sponsored by DigitalOcean. DigitalOcean makes it quick and easy to get up running with hosting your project. New users use the promo code GEEKERY to get $10 credit when signing up.

This episode is sponsored by’s Online Mentoring has just launched. It is step-by-step online mentoring that takes you from Clojure dabbler to Clojure professional. Sign up with the link to get 50% off the first month!


LambdaDays 2016 will be taking place on the 18th and 19th of February in Kraków, Poland. The CFP and registration has opened, so make sure to visit to find out more. And make sure to use code FunkyGeekz4dWin to get 10% off registration.

:clojureD 2016 will be taking place on the 20th of February in Berlin, Germany. The CFP has opened, so make sure to visit to find out more.

If you have a conference related to functional programming, contact me, and I will be happy to announce it.


About Rob Sullivan
How Rob went from DB to dabbling in app development
Rob Conery’s talk The Next Big Thing Or Cool-Kid Koolaid? Slicing Through The Rhetoric of MVC vs. WebForms
“Learning is cumulative [..] Everything builds on itself”
“Pretend I am an App Dev, get a job, and then take over the database”
Seeing the goodwill of the core contributors of Elixir is what attracted Rob to Elixir
First experience in Functional Programming with Clojure
“Keep your friends close, keep your enemies closer”
“I haven’t met a Clojurista who isn’t extremely smart and doesn’t care about their app”
“[Clojure] taught me and showed me there was something to Functional Programming”
Rob’s experience getting into Elixir
The benefit and fun of just playing with other languages with others
How Elixir got onto Rob’s radar
PostgreSQL is suddenly the bottleneck
The interest in the BEAM for day job from an Operations perspective
Rails’ Active Record vs Jeremy Evans’ Sequel
Feature richness of PostgreSQL and the problems of having abstractions that limit those features
Not having control of your PostgreSQL instance when deploying
PostgreSQL being the bottleneck in Elixir
Concurrency and isolation levels
Lack of current visibility about data access behavior in Elixir
Functional programming languages ability for massive concurrency when using the database
“Is it fair to attribute problems to Postgres when you’ve thrown it in a place with shared resources”
Microservices and the separation of reads vs writes against the database
Dealing with the differences of a “shared” vocabulary
Virtual User Groups
Paul Lamb
Benefits of smaller groups and lack of travel
“It pulls them out and gets them involved”
Throw Discourse on Digital Ocean
“Take a couple of hours to play with something new”
“Always email me at and I will reply within a month or two.”

As always, a giant Thank You goes to David Belcher for the logo design.


Code-forward Othello

Mark Bastian gave a thought provoking talk at the Conj about bottom up design. It triggered interesting conversations with my friends. I venture to say Mark exaggerate the top down object oriented approach, and I liked that he did, because it allowed me to think about the contrasts more concretely. One of my friends commented that it would be interesting to see how he would design his game if it had to support multiple rules. I thought it would be an interesting screencast... and have been wanting to show some devcards dual build usage for a while. So here it is, Tic Tac Toe to Othello:

Watch: Screencast (24 minutes)

Play: Game
Read: Code

Write: Another board game? Go? Checkers?

Transcript of screencast:

CoderX here.

In the last screencast we setup a ClojureScript project,
implemented a tic tac toe game, and published it online.
Today I want to show you how to work with a larger codebase.
We are going to convert our tic tac toe game into Othello,
focusing on our workflow along the way.

Othello is played on an 8 by 8 board with black and white discs.
Each player places their discs in such a way as to capture the opponent's discs.
When placing a disc, opponent discs that become surrounded are captured.
Captured discs are converted to the capturing player's color by flipping them.

Before we get coding let's add testing feedback to our workflow.
Don't worry, this won't be the boring style of testing you may be expecting!
But it will take some setup to get going.

First add a dependency to our project.clj
Devcards is a library that showcases our components in various states.
Copy the dev build section to create a devcards build.
Give it a different output directory,
so that the compiled files do not collide with other builds.
Create a devcards.html file,
Copy and paste the contents from the devcards README on github.
Start the new build we configured by typing:
`lein figwheel devcards`
Open localhost:3449/devcards.html
Seeing this page indicates that everything is working so far.
In the core.cljs source file, add devcards to the namespace require.
Refer the `defcard` macro.
Now define a card with some text in it.
The text can contain markdown; you can create titles and even format code.
Refer deftest from devcards instead of test.
See how our existing tests are now rendered into the page.

Failing tests are colored red.

Instead of `defcard`, we will be using a more specific version `defcard-rg`
which renders reagent components.

We can define a card that shows a single piece of the board in a given state.

Now we can isolate a single component to work on,
instead of having to observe the entire application.

We need a little more space here...
Let's show our existing pieces,
and adjust the sizing.

O.K. let's make some discs.

We'll use blue instead of white for now so that we can see the disc on a white background.
We need to pass the coordinates to place them in the right location.

Now we need a green background.
Let's copy the existing blank piece but make it green.
And the put blank pieces behind our discs.
That looks about right.
Let's parameterize the blank component so that it takes the background color.
We'll add an argument, but keep a default of grey if only 2 parameters are passed.
Does it work if we pass red?
Yes, great!

Let's make a card with a complete board.
We don't need the title and button, so let's extract just the board.

We'll change our convention slightly so that blank cells on the board are represented with a space,
then we can use a B for black disc and W for white disc.
Update the render cases to default to a blank.
The top left nine positions are currently being initialized to B,
because that was our tic tac toe starting condition.

Let's make a function to create a `new-othello-board`.
An Othello game starts with four pieces in the center in a diagonal configuration.

Now we will add another card to show the tic tac toe game.
We need to update `new-tictactoe-game` to use space instead of B.

Notice that we now have two cards that show the same component in two different states.
Adding cards and tests reduces our time spent clicking through the application while developing.

Our blank cells don't do anything when clicked,
because they are modifying the global app-state.
We'll make them update the state passed instead.

There is quite a bit of logic in this click handler, let's extract that into a function.
We'll need to pass a game atom through, so that it can be modified.
Checking the console for errors reveals that we forgot to pass an atom to our original card.
We can use an empty map atom for those, as they need not respond to clicks.

Our game atom needs a status, because we prevented further moves after a win or draw.
Great, we can now click on the tic tac toe board and see the game progress.
When we click on the othello board, we are still using tic tac toe rules.

It is time to implement the othello rules.
The objective in othello is to capture the opponent's discs by surrounding them.
Here are the valid moves white can make in response to my move.

Let's start with detecting which cells positions are valid moves.
And placing a disc instead of a naught.
To preserve the tic tac toe rules we need two separate logic paths that dispatch on the game type.
Multimethods are a good way to express this.
You can think of multimethods as case statements as functions.

`defmulti` declares a name and the dispatch function.
`defmethod` declares a function to call for a dispatch value.
`defmulti` needs to have the same signature as the methods.

To start with, let's constrain the othello `can-move?` function to cells that are adjacent to a white disc.
To dispatch by type, we need to give our games a type.
Let's convert our `new-board` function into a `new-game` function,
returning a map containing the game type, status and board.

Oh no, something went wrong:
`Uncaught Error: 4 is not ISeqable.`
Expand the stacktrace by clicking the triangle at the start of the error message.
Scan down the stacktrace to the 4th row:
`tictactoe$core$available_QMARK_` Means in the namespace `tictactoe.core`, in the function `available?`
`@ core.cljs?rel:96` is the filename and line number.
:96 tells us the problem is on line 96 of our core.cljs source file.
The line above indicates that the problem occurred when calling `get-in` from the ClojureScript core namespace.

Ah yes, get-in is expecting a vector containing i and j. Fixed.

Player moves are limited now, but we still need to apply the same restrictions to the computer's moves.
Let's rearrange a little so that we can call the same function from `computer-move`.
Put the `board-size` inside the game.
And the `background-color`.
After these changes, the board-size is not coming through to the `game-board`.
Aha... `game-board` takes an atom, so we need to dereference the atom to pull out the values we are interested in.
But the computer is still not making moves.
Let's print out what `can-move?` is doing...
That all looks fine.
Aha... we should be updating the game board here.

We can make `computer-move` more generic.
Convert `can-move?` to return the game that would result from the move.
Now `computer-move` is just the first successful result of `can-move?`,
when examining cells in a shuffled order.
The computer is now placing white discs when we place a black disc.
`can-move?` needs to be parameterized to behave differently depending upon who is making the move.

The movement rule for othello is more than adjacency.
An othello move is one that captures opponent discs between your move and one of your existing discs.
Captured discs are flipped over and converted to your color.
To check for a valid move we check for capture lines in every direction.
A capture line is a sequence of the opponents disc that is terminated with one of your discs.

Let's write a test to see if this definition is correct.
Given a board "space W W W B", placing a B at 0 0 should capture the 3 W discs,
capture should return the coordinates 1 0, 2 0, 3 0.
Given a board "B W space W B", placing a B at 2 0 should capture the 2 W discs on either side,
capture should return the coordinates 1 0, 3, 0.

We need to pass a game to our `computer-move` test.

Now we need the next game state to contained the result of flipping all the captured discs.
Hmmm looks like I missed the terminating disc requirement.
Let's add a failing test to capture that.
Given a board "space W W space", placing a B at 0 0 should not return any capture coordinates.
`capture-line` needs to collect a sequence of potential flips,
but only return them when we encounter a terminating disc.

Great, the move rules are in place now.
If we ignore the `win?` condition, it looks very much like othello.

Let's rearrange `win?` to be game specific.
Let's convert it into a multimethod on game type.
In othello, the player with the most pieces at the end of the game wins.

Players must make a capturing move if possible, or pass.
We can use the `frequencies` function to discover the count of space, W and B in the board.
`apply concat` flattens the board from a 2 by 2 matrix into a one dimensional sequence.
If there are no remaining spaces, the player is a winner if they have more discs than the opponent.
In a 2 by 2 game board, B B B W is a win condition for black.

Now that we have several tests, it is inconvenient to scroll through the page to view them.
Let's get some output in the console to alert us on failures.
In our `project.clj` in the devcards build under figwheel, add an on-jsload hook.
Add the test directory to source-paths, and create a source file run.cljs under test/tictactoe
`run` will call ClojureScript's `run-all-tests` function.
Well also define a method to print out success or fail when the tests complete.
Now we can see a summary of the tests in the browser console whenever we change code.

In othello it is possible to reach a configuration where neither player can move,
but not all cells are taken yet.
Let's extract an `available-moves` function so we can use it in both the `computer-move` and `win?` condition.
Hmmm even though we extracted it, our current `win?` code is much higher up in the file,
so we will need to rearrange our functions to get the order of declaration correct.

This is a symptom of a larger issue:
There is a lot of code in core.cljs now!
Let's think about how to split the code up into more coherent namespaces.

Clearly we have Tic Tac Toe specific code and Othello specific code.
`can-move?` and `win?` will go in there.
And we might create in the future some other game implementations.
Our core namespace should be kept pretty small.
Core will be focused on connecting a game state with the desired logic and a view.
We'll need a central definition of the logic of a game,
in which we can declare the multimethods which will be implemented by the more specific namespaces.
It will contain the code that is common across games.
We have a bunch of component drawing code which we can put in a view namespace.

Tic Tac Toe, Othello, and other implementations will depend on Game,
as they need the defmulti to connect methods to.
Core will depend on Game and View, and the implementations of `new-game`.
View won't need to depend on anything because it will just be rendering data.

O.K. let's move these functions to the appropriate namespaces!

We need a draw? condition.

By printing out the game in the console, we can see victory is reached.
Let's check tic tac toe is still working.

I think we are all set, let's play our game!
So far we have been running the devcards build,
We want to switch over to viewing the dev build.
In your terminal, interrupt the current build by pressing "control c".
Now run both builds simultaneously, by typing`lein figwheel dev devcards`.
Navigate to localhost:3449 to see the dev build.

We only want to mount the main game when viewing the dev build,
so let's put that inside a conditional.

Let's play our game!

Hmmm this is interesting, I cannot move, but the computer has already moved.
In this situation the computer should move again in the last remaining cell.
We can achieve this by making check-game-status recurse while there is no player move available.
Let's add a test to make sure our logic works.
Here is a small 3 by 3 board where there are 2 computer moves and no player moves.

Let's play some more games.
I think the victory message should be on a different line from the buttons.

A strong strategy when playing othello is to focus on positions instead of how many discs you can flip.
The most advantageous positions in othello are the corners,
which can never be lost and allow you to recapture long lines in many directions.
Next best are the sides, for the same reason.
When starting a game it is better to capture fewer discs,
This limits your opponents options, and allows you to force your way into a side or corner.
Once you can establish the safety of a side and corner, you will have many opportunities to reclaim the central discs.

Time to publish our boardgames.
Our project source files are now core, game, othello, tictactoe and view.
And we added a devcards.html file to the resources directory.

I created a new repository for the combined games,
so that there is a separate repository for each video.
But you don't need to.
I'll rename my output file to othello.js to differentiate it from my previous project.

Let's check that the minified build still works.
Interrupt the current build with "control c"
and type `lein cljsbuild once min`
open index.html if you want to check it locally.
Commit and push to the gh-pages branch.
Navigate to to see your page.

Let's review:
We converted our original game into two games.

The othello namespace contains our game specific rules for othello:
An othello game has a green background, the player is B, and computer is W.
The board has four discs in a diagonal configuration at the center.
Valid moves capture one or more lines of discs of the other player.
A draw occurs if there are no available moves to the player or computer.
We can shorten this test by using a new-board instead of repeating the values.
A win occurs when neither player can move, and one has more discs.

The core namespace has the game selection view and attaches the rendering.
The view namespace has the blank, circle, cross, discs, and game-board component.
The game namespace declares the multimethods that will dispatch by game type,
and some logic functions which are common between games.
The tictactoe namespace contains implementations specific to Tic Tac Toe.

We have a minified build which is published on github pages,
a dev build, and a devcards build.
Devcards presents cards and tests that occur in our namespaces,
so that we can see what our components will look like in predefined states.
We added an on-jsload hook to report a test summary to the console while developing.

If you have any questions, please drop a comment.

Until next time, keep coding!


Rendering Reagent on the Server using Hiccup

I recently watched a great talk titled Optimizing ClojureScript Apps For Speed, where Allen Rohner discusses the benefits and hurdles of server-side rendering.

React supports hooking in to server generated HTML at runtime. However, since React is a JavaScript library it becomes problematic to leverage this functionality from Clojure. While the JVM provides a Js runtime with Nashorn, it's extremely slow and requires a lot of twiddling to work for even basic examples.

Another approach is to run an instance of Node.js and farm out React rendering to it. This avoids the limitations of Nashorn, but introduces a host of new problems described in the talk.

Allen then proposes an alternative approach where he implements parts of the Om API and cross-compiles the components that way. You can see how this works in his Foam library.

The main difficulty identified in the talk is in implementing a sufficient amount of Om API in order to generate HTML on the server.

This got me thinking about what it would take to leverage this approach using Reagent. Unlike Om, Reagent has a tiny API and the only part of it used to create components is the Reagent atom implementation. The components themselves are written using plain Hiccup syntax.

Let's see how this could work. We'll start by creating a new Reagent project:

lein new reagent reagent-serverside

Next, we'll add a new namespace in called reagent-serverside.home src/cljc/reagent_serverside/home.cljc. This namespace will house the home page component that we'll pre-render on the server.

All we have to do now is to use a reader conditional to only require the Reagent atom during ClojureScript compilation:

(ns reagent-serverside.home
     (:require [reagent.core :as reagent :refer [atom]])))

We can now write our components as we would normally:

(ns reagent-serverside.home
     (:require [reagent.core :as reagent :refer [atom]])))

(def items (atom nil))

(defn item-list [items]
   (for [item items]
     ^{:key item}
     [:li item])])

(defn add-item-button [items]
   {:on-click #(swap! items conj (count @items))}
   "add item"])

(defn home-page []
  [:div [:h2 "Welcome to reagent-serverside"]
   [add-item-button items]
   [item-list @items]])

We'll have the items atom to house a collection of items, an item-list function to render it, and the home-page function that will use the item-list component. We also have a button that lets the user add new items with an :on-click event. This is all standard Reagent code.

Rendering on the Server

Now, let's navigate to the reagent-serverside.handler namespace and reference the reagent-serverside.home we just created.

(ns reagent-serverside.handler
  (:require ...
            [reagent-serverside.home :refer [items home-page]]))

We'll now have to write the functions that will traverse the components and render them as appropriate. We'll attach a :data-reactid key to each one to give it an identifier that React looks for, and inject the result into our Hiccup markup.

(defn react-id-str [react-id]
  (assert (vector? react-id))
  (str "." (clojure.string/join "." react-id)))

(defn set-react-id [react-id element]
  (update element 1 merge {:data-reactid (react-id-str react-id)}))

(defn normalize [component]
  (if (map? (second component))
    (into [(first component) {}] (rest component))))

(defn render
  ([component] (render [0] component))  
  ([id component]
    (fn? component)
    (render (component))    

    (not (coll? component))
    (coll? (first component))
    (map-indexed #(render (conj id %1) %2) component)
    (keyword? (first component))
    (let [[tag opts & body] (normalize component)]
      (->> body
           (map-indexed #(render (conj id %1) %2))
           (into [tag opts])
           (set-react-id id)))
    (fn? (first component))
    (render id (apply (first component) (rest component))))))

(reset! items (range 10))

(def mount-target
  [:div#app (render home-page)])

The render function will recursively walk the components evaluating any functions it finds and assigning the React id to each element.

Next, we'll set the items atom to a range of numbers, and then call render inside the mount-target to generate the markup.

Rendering on the Client

Finally, let's navigate to the reagent-serverside.core namespace in the src/cljs source path. We'll update it to reference the home namespace we created and render the home-page component on load.

(ns reagent-serverside.core
    (:require [reagent.core :as reagent :refer [atom]]
              [reagent-serverside.home :refer [items home-page]]))

(defn mount-root []
  (reagent/render [home-page] (.getElementById js/document "app")))

(defn init! []
  (reset! items (range 20))

When we load the page we'll immediately see the server generated markup and then it will be updated by Reagent when ClojureScript is loaded. There are a few caveats here that you should be aware of.

Any components you wish to render on the server have to be written in cljc, so you may end up having to add some shims for things like Ajax calls.

The component syntax has to work with both Reagent and Hiccup, so you have to be mindful to use the common subset.

React is fairly picky about the structure and the data-reactid tags. So, it can be tricky to generate a DOM tree that it likes. The example in the post will give a React warning about the DOM being different. Some more work is needed around this.

However, even in the case that React doesn't reuse the DOM, the user will see the page immediately and you'll get the benefits of SEO for your site.

Full source is available on GitHub.


Overall, I'm very happy with the results and it looks like it would be fairly easy to wrap this up into a library. The data focused approach is a huge win for Reagent here in my opinion. Since the components are laid out using regular Clojure data structures there's no need to implement any special API and things just work out of the box.


Learning Clojure: Error messages

I started my recent Clojure talk by enumerating the “scary bits” for new users. The two I went into were the fundamentally different semantics, and that the doc strings for the core functions were succinct and exact, but not expansive in use cases.

There was one that I forgot to bring up, though: compiler error messages when there’s a problem with a macro call.

There’s been a lot of chatter on the topic this past week, since Colin Fleming gave a talk at Clojure/Conj on the subject focusing on how to improve them with grammars. The conversation has kept a positive focus on how to fix it, as opposed to piling negativity on the situation (go Clojure community!) but that does not mean we can expect to see a change right away.

I’d like to address how this might affect you if you’re just getting into the language, and what you can do about it.

To avoid repeating Colin’s points, you may want to check the examples he gives at 6’34” into his talk.

Colin Fleming clojure errors

One thing struck me when I saw these examples: how weird it was that I completely forgot about this issue when preparing my talk.

I suspect it’s one of those things that you learn to live with, having learned to sometimes scry the root cause from the spilled entrails of an error message, so it slipped my mind. Perhaps that’s the reason why it hasn’t been addressed yet - as you get more experienced with the language, you learn to interpret these edge cases. Experienced people forget it’s a pain point for newcomers, and you need to be very experienced if you’re going to be able to contribute a fix.

It’s a similar case to the one I brought up when talking about the into doc string which, in case you don’t know it by heart, reads:

Returns a new coll consisting of to-coll with all of the items of from-coll conjoined. A transducer may be supplied.

How I phrased it at the time was that the doc string tells you exactly what the function does, but nothing beyond that. It does not give any other information that might help someone who’s just getting into Clojure, curious about what this function does, or who might not be familiar with the fact that conjoin - available in Clojure as conj - has a specific, collection-dependent behavior.

The situation with macro error messages, as Colin points out, is not that they’re spewing out an incomprehensible error. They’re telling you exactly what went wrong in the macro. They are not, however, telling you something that would help you find where the problem is in your code.

The question is… will this be a show stopper for you as a newcomer?

I’d say I don’t expect it to be, but would need to add a huge asterisk right besides it.

The asterisk comes from the fact that Clojure’s small syntax can make it easier to eyeball where a problem is, but you need to take the time to get used to it. You need to interiorize that, to use defn as an example, the brackets following the function name are not some peculiar syntax construct, but an actual vector being passed as the second parameter to a macro.

I’ll admit this is easier said than done, and an offshoot of Clojure being simpler than you expect. Even after two years with it, my brain keeps expecting half of what I see to be case-specific syntax. It’s hard to deprogram yourself.

This will, however, bite you particularly hard if you expect to learn Clojure by jumping in and hacking on a project template, something I already warned against. If you attempt to cargo cult the learning process by modifying bits of code in a large program, chances are any errors you trigger will stump you all the way back to Java.

If instead your first programs are small functions, you’ll get much better acquainted with the language, and will have an easier time spotting where you’ve made a mistake when you stumble upon one of these.

It bears repeating. You need to start small.

Get a book so you can learn the basics. Don’t try to jump to something topic-specific (Clojure for web apps!, Clojure for financial analysis!, Clojure for Chrome extensions!) right away. And more importantly, practice.

The advantage of doing the 4Clojure exercises is two-fold. First, it’ll get you used to the Clojure way of thinking. Second, it will provide an opportunity for you to try your newly acquired skills in a localized setting. If you ever trip one of these obscure-sounding errors, you’ll get to see it in the very specific context of the problem, making it easier to realize what your mistake was.

By the time you feel ready to move on to working on larger problems, you may forget that was ever an issue.

I don’t mean to sound like an apologist. It’s something that definitely needs to be addressed if Clojure is going to have a smoother learning curve, which is fundamental for adoption. Things will improve, however, and I expect they will improve rapidly. All the work Colin has done for Cursive - a superb Clojure plugin for IDEA - is not Cursive-specific, and the community as a whole can benefit from it.

Meanwhile, keep it small, and practice!


Clojure Gazette 151: Top Down, Emacs, CQRS

Clojure Gazette -- Issue 151 - November 23, 2015

Top Down, Emacs, CQRS
Read this email on the web
Clojure Gazette
Issue 151 - November 23, 2015

Hi Clojurists,

The Conj happened this past week, and I forgot to remind everyone to keep an eye out for the videos. Sorry about that! But they're out now.

I really liked the Conj videos. I really like being at conferences and talking to the awesome attendees. But I think I like watching videos online better than I like watching the talks live.

There is usually an overarching theme for the Conjes, but I haven't found it yet. I'll keep my eye out and keep you informed. I've selected a few talks in this issue and some other content I found interesting this week.

Please enjoy the issue!

Rock on!
Eric Normand <>

PS Want to get this in your email? Subscribe!
PPS Want to advertise to smart and talented Clojure devs?


Sponsor: Boot

As much as we talk about data-driven programming and declarative langauges, sometimes regular code is the best way. What's the best way to represent a series of steps needed to build your project? I suggest procedural code. Boot is a build tool for Clojure that gives you the power of the entire Clojure language to write your builds. Instead of a DSL with plugins, it's a library with composable abstractions. Check it out and give a shout-out to the maintainers on the forum.

Bottom Up vs Top Down Design in Clojure Youtube

Mark Bastian gave a great talk at the Conj which is on a topic dear to my heart: avoiding complexity while programming. He constrasts the OO approach of building a giant class hierarchy that does nothing with building up data models to represent your domain. My big takeaway was that modeling relationships like "isa" and "hasa" is usually pointless if they aren't important in your domain.


Tupelo is a convenience library--lots of routines for doing common things. This kind of library is always interesting. While I usually don't use them wholesale, they often have little nuggets of usefulness.

Why I Choose ClojureScript

Eric Shull calls upon the idea of looking for bright spots to explain why ClojureScript is right for him.

Onyx 0.8.0 Released

Onyx is a distributed computation system built in Clojure. It's maturing quickly and promises some great things.

Clojure, Emacs and Cider

Oh, my! Setting up Emacs for use with Clojure is a lot of work. I'm really sorry about that but it's the truth.

Om Next Youtube

David Nolen's talk at the Conj was about Om Next, the successor to the current Om. He explains the problems it is trying to solve. It will, of course, be popular.

A Deep Specification for Dropbox Youtube

Benjamin Pierce is a legend in our field. He wrote the book on programming languages. This talk was very interesting because he specifies a practical service (Dropbox) using formal notation. He was able to test it using generative testing.

From REST to CQRS with Clojure, Kafka, & Datomic Youtube

Bobby Calderwood's critique of CRUD is spot on. The main point is that CRUD operations don't map to user operations. When was the last time you CREATEd a transaction at your bank? No, you most likely thought of it as transfering money. Why do we try to funnel everything through the CRUD verbs? Calderwood proposes a universal mechanism for recording user events (such as transfering money) which gives a real abstraction.

The ClojureScript Compiler - A Look Behind the Curtains Youtube

Maria Geller has been working on the ClojureScript compiler as part of the Google Summer of Code. In this talk, she explains how the compiler works.


Update on tdd-mode with CIDER

I can’t write a whole new post this week due to being buried under some once-in-a-lifetime stuff. Still, the Monday post is one I refuse to miss, so I leave you today with an update on last weeks post.

Running tests on file save really didn’t work out for me, because I’ve configured CIDER to save files before loading them when I use cider-load-file. So the tests were always being run against outdated definitions.

The fix is simple, though. Just run the tests after load-file. CIDER even had a hook for that already. I also made the minor-mode global (even though it only applies to clojure buffers) so that it’s easier to disable everywhere with a single command.

The new code is in the original post.

Comment on this.


Copyright © 2009, Planet Clojure. No rights reserved.
Planet Clojure is maintained by Baishamapayan Ghose.
Clojure and the Clojure logo are Copyright © 2008-2009, Rich Hickey.
Theme by Brajeshwar.