Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Timothy Pratley, who currently works for Tideworks Technology as a Development Manager building Traffic Control software for logistics clients including SSA Marine, CSX, and BNSF.

Interactive development is a big win. Being able to evaluate snippets of code without building and running your entire project makes it faster to test code. Being able to modify code and data in a running system allows you to experiment with data and operations immediately. Clojure is an environment you can interact with through a Read Eval Print Loop (REPL). To learn more about Clojure, watch the Clojure Inside Out video. Where the waters get murky is when it comes to tooling, and how to leverage the potential productivity boon. In this post, I will share with you the workflow that works best for me. Together, we will work through a basic example of interactive development. To follow along, please first install Leinigen and Light Table. Feel free to download the full source code for this post.

1. Create a project called interact

Start by opening a command window. Change the directory to where you want to create the project and invoke Leiningen to create it:

2. Add the directory to the workspace

Launch Light Table. From the view menu select workspace. Click “folder” and enter or browse to the “interact” directory. The interact folder now appears in the workspace tree view, so click on it to expand, then expand src/interact and open core.clj.

You will see this:

fig1

3. Evaluating Code

Press CTRL-SHIFT-ENTER to evaluate the entire file. You will see “Connecting” appear at the bottom of the screen. Light Table is starting a REPL which is connected to your editor. It takes 10 seconds or so the first time, so be patient, you only have to wait once. When it is done you will see nil in blue near the (ns interact.core) line, and #’interact.core/foo near the function definition. These are the results of the evaluation.

Now at the bottom of the file type (+ 1 2) press CTRL-ENTER to evaluate the current form. 3 is displayed in blue near the form, indicating the result. See how fast it was that time?

fig2

4. Fixing errors

Try calling the existing foo function by typing (foo) on a new line and pressing CTRL-ENTER.

Oh no, we forgot to pass in an argument! We get some red text telling us the error of our ways:

fig3

Enter your name as an argument to the foo function (foo “MyName”) and press CTRL-ENTER to evaluate the new code. The error goes away. But where is the output? It went to the console, where println output goes. From the View menu, select console. At the bottom of the window you will see your greeting.

fig4

Now create a new function:

And call it:

To see a nested error:

fig5

The error is not where we call bar. Scan down the stack trace to the first occurrence of interact.core and see the line number (in this example it is line 12). We need to do some navigation to find the error. The bottom right of the window shows the current line and character of the cursor. You can move your cursor to the correct line, but there is a faster way. Press CTRL-L to see a command tab on the right side of the window. Type 12 and press enter, we are now on the offending line and can make the fix.

CTRL-SPACE opens the command list that shows you all of the commands Light Table has, and their shortcut keys where appropriate.

5. Write code

Now I want to draw some pendulums. According to Wikipedia I can approximate the movement of a pendulum as:

fig6

angle(t) = initial * cos(2*PI / period):

After evaluating Tau and phi we naturally want to know how this function behaves. Given some time t and a period T, it should return the pendulum angle:

Starting at t=0, the pendulum is at angle 1, and it then proceeds down to the opposite extreme of -1 at t=50, finally returning to 1 at t=100 given a period of 100. It also works for t=150.

To draw the pendulum we now need to add a dependency on a drawing package.

6. Using a library to do the heavy lifting

Open the project.clj file and add [quil "1.6.0"] to :dependencies.

From the View menu, select connections. Click disconnect. Re-evaluate the namespace. A new connection is made with the dependencies loaded.

It is now time to define how to draw a pendulum:

We need to calculate the period from length in order to calculate phi:

Let’s show more than one pendulum at a time:

Now we can start drawing:

Evaluating all of the code so far, we get a blank window pop up. Leave it open. It is time to start adding pendulums:

We can modify the draw-pendulum function and re-evaluate it and see the image affected in real time. Here is a video showing some things we might try, like changing the size and shape of the pendulum:

http://www.youtube.com/watch?v=JKQZpVJQRT0

The pendulums make harmonic patterns if we make them swing with an integer frequency relative to some total time before they will all align:

7. Use a test watcher

Let’s open the project.clj file again and add the following:

Find your command window and type:

Midje will now detect any changes to the source code or the test code, reload them, and run all of the tests. The thing I like the most is that it checks compilation upon save. Even if I have no tests, I will get an error message if I save the file. Try it out, by adding an unmatched parenthesis to your source file and press CTRL-s to save. In the command window the following will appear:

Now is a good time to migrate some of my exploratory code from core.clj to core_test.clj, and add some sanity checks:

8. Refactor core, use a scratch pad

When I save any changes to core.clj, the autotest listener is evaluating it and popping up a new sketch window. Annoying! This is a symptom of having functionality mixed up with invoking it as we please. It is time to separate out the functionality of our project for drawing pendulums from the calls that create a window and add pendulums.

Create a new folder in the project called repl, and create a file scratch.clj inside it. Because it is not in “src” or “test”, midje autotest will not reload it when it changes. Refactor sketch into a start function, and the harmonic pendulum creation into create-harmonics in “core”, then call those functions from “scratch”.

When we save code in core, midje checks it. When we evaluate code in core, it affects the live session. I do these two things a lot, so I rebind CTRL-SHIFT-ENTER to both save and then evaluate. To do this press CTRL-SPACE to open the command list. Type settings and select “User keymap”. Add “ctrl-shift-enter[:save :eval-editor] and because I like to show/hide the workspace “ctrl-t[:workspace.show].

Right click on the area near “core.clj” to create a new tabset, and you can have both side by side:

fig7

Notice that by including clojure.repl and clojure.test in the “scratch” area, you get access to repl commands like doc, and can run tests manually if not using autotest.

The REPL code in scratch gets migrated to tests, core, or new namespaces as things progress. We have everything in place to code away productively on a project with instant feedback.

Conclusion

Clojure really shines in interactive development. Light Table offers a compelling interactive development experience in a very approachable way. I highly encourage you to try it out for yourself. Take advantage of the productivity gains that come from having a REPL in your editor.

Be sure to look at the Clojure resources that you can find in Safari Books Online.

Safari Books Online has the content you need

Clojure Inside Out is a video where you’ll not only learn how to tackle practical problems with this functional language, but you’ll learn how to think in Clojure—and why you should want to. Neal Ford (software architect and meme wrangler at ThoughWorks) and Stuart Halloway (CEO of Relevance, Inc.) show you what makes programming with Clojure swift, surgical, and accurate.
Clojure Programming, helps you learn the fundamentals of Clojure with examples relating it to the languages you know already—whether you’re focused on data modeling, concurrency and parallelism, web programming, statistics and data analysis, and more.
The Joy of Clojure goes beyond the syntax, and shows how to write fluent, idiomatic Clojure code. You will learn to approach programming challenges from a Functional perspective and master the Lisp techniques that make Clojure so elegant and efficient. This book will help you think about problems the “Clojure way,” and recognize when they simply need to change the way they program.
Practical Clojure is the first definitive reference for the Clojure language, providing both an introduction to functional programming in general and a more specific introduction to Clojure’s features. This book demonstrates the use of the language through examples, including features such as STM and immutability, which may be new to programmers coming from other languages.

About the author

timhead Timothy Pratley currently works for Tideworks Technology as a Development Manager building Traffic Control software for logistics clients including SSA Marine, CSX, and BNSF. He can be reached at timothypratley@gmail.com.

Tags: Clojure, Interactive, Leinigen, Light Table Workflow, pendulums, phi, Read Eval Print Loop, REPL, Tau,

6 Responses to “Light Table Workflow for Interactive Clojure Development”

  1. Mike Hayes

    Great article – I’ve been a bit befuddled about how to setup projects with LightTable and this really helped!

    Could you add a couple of lines in part 6 about having to “:use quil.core” and evaluate it?
    I’m a relative noob with clojure but I have done some processing so I understood why I was getting errors about frame-count.
    It might not be obvious to someone without processing knowlegdge

  2. Tom

    Really good article but I cannot run the example. I am new to Clojure and LT (and throwing quil into the mix has me a bit stumped). Could you post up the full code from the example for me to eliminate a simple cut-n-past error?

    Thanks

  3. Chris

    This is awesome! The LightTable docs are definitely still a work in progress, and I couldn’t figure out how to set up watches or really use its interactive powers.

    I do have one issue. I’m setting up a website and having trouble doing things interactively. For instance, if I want to test how my site handles a request, I have to kill lein and restart it in order to get it to recognize my changes.

    I feel like Clojure is supposed to be easier than that (I don’t have to shut down my python server every time I make a change). Is there a way to use LightTable for this kind of thing?

  4. Nikita Dudnik

    Great article, thanks!

    I second the request of clarifying the step about the quil library. (:use quil.core) is missing from the post. Please add.