Try Three Times

Summary: Distributed systems fail in indistinguishable ways. Often, retrying is a good solution to intermittent errors. We create a retry macro to handle the retries in a generic way.

Let's face it: your system is probably a distributed system. All web apps are by definition distributed. They have at least one server, probably a separate database server, and many browser clients. And now microservices are getting popular. Distributed is the current and future normal. While Clojure solves the problems of multiple cores sharing memory at the language level, distributed systems problems are left to be addressed at the application level.

The problem

One big problem that comes up all the time in distributed systems is dealing with failure. Failure happens everywhere. The problem in a distributed system is that you don't know where the failure happened. For example, let's say you make an HTTP GET request and 20 seconds later, you're still waiting for the response. Is it:

It is literally impossible to know what the problem is. And that's ok. There's a lot of machinery between one machine and the next. Even if you could diagnose the problem, are you really going to program each error case?

Metaphor

Let's say you call your friend and they don't pick up. Are they asleep? Is their phone off? Did the call not go through? The phone won't tell you. And you really want to talk to them. So what do you do? You call back. You might even call back a couple of times. If they pick up when you call back, great! If not, then you get tired and give up.

That's a common approach in distributed systems as well: retry your distributed message a few times before you give up. It's easy and fixes a surprising number of problems. What's more, there's a good solution that's simple in the Hickeyan sense.

The solution

Failure in Clojure typically means an Exception. So we'll need to catch exceptions and run code multiple times.

(defn try-n-times [f n]
  (if (zero? n)
    (f)
    (try
      (f)
      (catch Throwable _
        (try-n-times f (dec n))))))

You pass it a function and a number of times to retry it. The base case is when n is 0. In that case, it will just try it (not retry). If it's greater than 0, it will wrap the function call in a try/catch, catch everything, and recurse. If after n retries, is still throws an exception, try-n-times will fail and some other code will have to deal with it. The concern of retrying is separated from what is being retried.

How do you use it?

Wrap your distributed calls in this bad boy and you're good to go.

Instead of this:

(http/get "http://somewhat-reliable.com/resource"
          {:socket-timeout 1000
           :conn-timeout   1000})

You do this:

(try-n-times #(http/get "http://somewhat-reliable.com/resource"
                        {:socket-timeout 1000
                         :conn-timeout 1000}) 2)

Remember, n is the number of retries. So that's 1 try + 2 retries.

Macro, anyone?

Alright, yes, I made a macro for that. It does come in handy to have a macro that you can put code in instead of passing in a function.

(defmacro try3 [& body]
  `(try-n-times (fn [] ~@body) 2))

This one is used like this:

(try3
  (println "trying!")
  (do-some-stuff))

Add it to your Clojure Emacs config so it formats it nicely:

(put-clojure-indent try3 1)

Warning

Now, a little care needs to be taken when you use this. Remember, when you get a failure, it could be a timeout. The server could be processing your request. Or it could have failed halfway through a multi-step process. What that means practically is that your distributed message has to be idempotent. HTTP GET is idempotent, so it's ok. POST generally is not, but sometimes it is. Use your judgment! Also, you should make your call timeout, to turn long waits into errors.

Conclusion

This pattern is just one piece of a larger distributed system puzzle. The network and servers are unreliable. They might work the whole time during development, but in the fullness of time, an always-on distributed system will have some kind of failure eventually. Sometimes the failures are temporary, and in those cases, a quick retry can fix it right away.

Though Clojure does not have specific solutions to distributed systems problems, coding them up is short and straightforward. If you're interested in learning Clojure, I suggest you check out LispCast Introduction to Clojure. It's a video course that uses animation, storytelling, and exercises to install Clojure into your brain.

Learn Functional Programming using Clojure with screencasts, visual aids, and interactive exercises
Learn more

You might also like

Data-First Programming

Summary: If something is important, you should deal with it sooner and more often. That's the approach Clojure takes to data representations. It means serialization of internal data is a non-issue.

Netflix has a counterintuitive but brilliant system called Chaos Monkey. Chaos Monkey will randomly kill services. It is trying to simulate, in the microcosm of a business day, the craziness that happens in the production macrocosm. Services die, servers fail, latency spikes, and networks partition. It might not be soon, but eventually it will happen. Better deal with it now, when people are at work to deal with it. Chaos Monkey encourages you to write your code to work in such a chaos-filled environment so that unexpected failures are a breeze. The idea is an instance of the more general principle of "if something is important, deal with it sooner and more often".

There's something related to this idea of surfacing the errors early that I've been thinking about. It's about data. Have you ever written some classes and everything is well and good. And then after a while, you need to serialize that to disk or across a network. Now you have to come up with some format (maybe JSON or XML) to represent your class. Then, whenever the class changes, you have to remember to change the data format to keep them in sync. It's kind of painful!

Well, I'll tell you, that rarely happens in Clojure. Because in Clojure, you often start with data structures. Meaning, you're already thinking in data, modeling in data, and working in data. Serialization becomes a non-issue, because Clojure data structures come built in with readers and writers. Just like causing errors to happen early because they will happen eventually, Clojure programmers code in data in part because you're going to need data (serialization and deserialization) eventually.

If this idea intrigues you, you may want to check out Clojure. Its data structures are cutting edge! Check out LispCast Introduction to Clojure if you would like to get into functional programming using animations, exercises, and screencasts.

Learn Functional Programming using Clojure with screencasts, visual aids, and interactive exercises
Learn more

You might also like

The Paper Metaphor

Summary: Functional programs follow a simple rule: never write on the same paper twice. Imperative programs are free to define their own rules. Both have interesting consequences.

I just read Functional Programming for Everyone Else by Emily St. It's a good read about the fundamental differences between Turing Machines and Lambda Calculus. Near the end, she mentioned this:

I think of functional programs as ones which do their jobs without stopping to take notes along the way.

That got me thinking of the metaphor of taking notes. It's an interesting metaphor, because as she mentions in the article, modern computers are based more on Turing Machines, with their tapes (notes), rather than Lambda Calculus. Lambda Calculus being abstract instead of mechanical (what instead of how), it doesn't show its work.

In the spirit of more perspectives being better than fewer, I'd like to give my metaphor, inspired by idea above. Functional programs are those that have a very simple rule: never write on the same paper twice. In Turing Machine terms, it means never write on the same piece of tape twice. This rule is simple enough that you can build it into the compiler and runtime to enforce it. In programming language theory, we call this immutability. Once a paper is written on, it is immutable.

Imperative programs, on the other hand, don't have such a rule. They can write on any piece of paper, even write over or erase what's written. They rely on their own code to enforce rules for how to organize these pieces of paper so that it still makes sense. They might use locks, which are notoriously hard to get right.

The nice thing about functional programs is you get a nice record of what's happened. You can step through all of the intermediate work because it was never overwritten. It's like an artist keeping their old sketches that led up to their masterpiece. Imperative programs are like finding out that it was all done on the same canvas, art painted over art, irrevocably lost. There is no xray to uncover it.

The other nice thing about functional programs is multiple programs can share the same stack of paper. Since they're following a rule, they will never overwrite someone else's work. But imperative programs need to have complex coordination rules to make sure that they aren't writing on the same page at the same time, or overwriting something that someone else will need.

If you'd like to learn Functional Programming, I can recommend LispCast Introduction to Clojure. It will teach you Functional Programming using Clojure, animations, and screencasts, along with many exercises.

Learn Functional Programming using Clojure with screencasts, visual aids, and interactive exercises
Learn more

You might also like

On sale now: Intro to clojure.test Early Access

Summary: LispCast Intro to clojure.test is on sale now for a limited time through the PurelyFunctional.tv Early Access Program.

Update: PEAP is now closed for Intro to clojure.test. Sign up below to find out when the finished product is published.

Folks, it's happening. I just opened up the PurelyFunctional.tv Early Access Program for LispCast Into to clojure.test. If you like to be on the cutting edge or get lots of access to the teacher, now's your chance. Open for 48 hours only!

You might also like

PurelyFunctional.tv Early Access Program

Summary: The PurelyFunctional.tv Early Access Program is a way to make courses in a more iterative and interactive way. I'll be publishing Intro to clojure.test this week under PEAP.

Computers and the Internet have allowed people to produce better products than has ever been done. Photography is better because of Flickr. Handmade knives are stronger and sharper than ever. Stone arrowhead making is better than ever. People are able to experiment, share their results, and learn the results of others faster than ever before, because the Internet allows them to communicate faster.

It's simply a matter of speed and accessibility. I want to bring that speed and accessibility to LispCast courses. I have been working hard on building a platform for me to develop courses iteratively. That means I can make them in smaller steps. The other piece is the feedback, where I ask you, my awesome customers, to borrow your brain for a bit. Talk about what works for you and what doesn't. I'll listen, answer questions, discuss them with you, and incorporate what I learn into the course.

Everyone wins. You get to learn what you need to learn faster, with your questions answered. And I get to make the course better for everyone. Seems like a good deal.

I'm creating what I'll call the PurelyFunctional.tv Early Access Program. It's simple. As soon as a course has a bit of content and interest, I'll post it up for sale. You get to download the course in a first draft. Let me know what questions you have, where you're having trouble, or things that were too easy. I'll continuously work those things in, and let you know when to download the new one.

I'll throw in another small benefit: if you're part of the PEAP, meaning your buy the course before it's finished, I'll put your name in a Thank you page in the course and on the course information page. Everyone who goes there will be able to see it.

To kick off the Program, I'm going to be publishing LispCast Intro to clojure.test, in its current state, this week. Entry into the Program will be available for a limited time. So sign up below if you'd like to be a part of it. I'll send out an announcement with the instructions.

You might also like

Hiccup Tips

Summary: Hiccup is a Clojure DSL for generating HTML. If you're using it, you might like these tips.

Hiccup is a Clojure Domain Specific Language (DSL) for programmatically generating HTML. It's one of the three tools I recommend in my Clojure Web stack. It's a thin layer over HTML, but oh, how I welcome that layer! The biggest win is that since it's an internal DSL, you can begin abstracting with functions in a way that you will never be able to, even in templating engines.

Hiccup is an example of a great Clojure DSL. It uses literal data structures pretty well, it's as or more readable than what it translates into, and, as a layer of indirection, solves a few sticky problems of HTML. If you don't know it, go check out the Clojure Cookbook recipe for Hiccup. Hiccup might take some getting used to, but once you do, you'll appreciate it.

This article will assume you are familiar with the syntax and want to up your game.

Cross-site Scripting Vulnerability

Ok, this one is a pretty bad problem. Hiccup generates Strings, just plain old Java strings. If you put a String in the body of a Hiccup tag, it will just concatenate it right in there, no questions asked. That's just asking to be exploited, because that String is going to be shipped off to the browser and rendered, scripts and all.

Most templating libraries will default to escaping any String you pass them. The non-default, usually obviously marked alternative is to pass in a String unescaped. Hiccup got this backwards and it just sucks. It means you have to do extra work to be secure, and if you forget just once, your site is vulnerable.

The fix: This is the work you have to do every time you're getting a String that could be from the "outside" (a form submission, API request, etc.). Normally, you'd do this:

[:div content-of-div]

That will work but it's unsafe. You should do this:

[:div (h content-of-div)]

That little h (hiccup.core/h to be exact) there means escape the String. It sucks, but that's how you do it in Hiccup. One day I want to write a secure fork of Hiccup.

Overloading vectors

One downside to Hiccup and any DSL that overloads the meaning of vectors is that vectors are no longer useful as sequences within Hiccup. They now mean "start a new HTML tag". It's not a huge deal, but I've spent a lot of time debugging my code, only to realize that I was using a vector to represent a sequence. I use literal vectors everywhere else (because they're convenient and readable), but in Hiccup land they're wrong.

The fix: You can't use a literal vector, but you can call list to create a list. Not as beautiful, but it is correct. Sometimes I will call seq on a return value to ensure that it's never a vector.

Multiple tags

I don't know why this still happens, but it's common, so I'll mention it. Sometimes I'll be looking at the HTML output in a browser and I just can't find an element. It's gone. Reload, still not there. When I look through the code, the hiccup to generate the tag is right there! Why won't it render?

Well, long story short, it's because in Clojure, only the last value of a let or fn is returned. Doh! My missing element was being rendered then discarded.

(defn list-with-header [header items]
  [:h3 header] ;; this header is missing
  [:ul
    (for [i items]
      [:li i])])

The fix: Wrap the two (or more) things in a list (not a vector!).

(defn list-with-header [header items]
  (list ;; wrap in a list, not a vector
    [:h3 header] ;; now it's there
    [:ul
      (for [i items]
        [:li i])]))

Hiccup plays nice with nil

This one is just a little design touch with some perks, not a problem that it's solving. In Hiccup, the empty list renders nothing. This is extended to nil as well. A common thing in HTML is that you want to render a bunch of children in a parent tag, but you don't want the parent tag if the list is empty.

Standard constructs will render the parent tag:

[:ul
  (for [i items]
    [:li i])]

When items is empty, you still get <ul></ul>. This is a problem with lots of templating libraries.

The fix: The fix in Hiccup is due to it playing nice with nil. Wrap the parent in a when:

(when (seq items)
  [:ul
    (for [i items]
      [:li i])])

It's not beautiful, but then again, you could be using HTML with Moustache.

Use defn for snippet abstraction

HTML has no way to abstract. The crap you see is the crap you get. Many templating libraries have some kind of snippet concept, often referring to different files. Well, because Hiccup is just code inside of Clojure, you've got a better designed way of making reusable pieces of Hiccup.

Let's say I'm repeating something a lot:

[:div
  [:ul
    (for [i list1]
      [:li i])]
  [:ul
    (for [i list2]
      [:li i])]
  [:ul
    (for [i list2]
      [:li i])]]

That ul is basically the same three times.

The fix: Standard functional abstraction. Pull out the repeated bit into a new, named function.

(defn make-list [items]
  [:ul
    (for [i items]
      [:li i])])

Now you can call it from inside of Hiccup:

[:div
  (make-list list1)
  (make-list list2)
  (make-list list3)]

Compiling your snippets

You may know this, but Hiccup is a compiling macro. That means it takes your literal vectors, maps, etc, and at compile time, generates code that will generate your HTML. All this means is that Hiccup is really fast, about as fast as concatenating strings can be.

But, because the Hiccup compiler doesn't do a full examination of your code, it can't compile everything. It inserts run time fallbacks for stuff it can't handle at compile time which will interpret it at run time. So, for instance, if you're calling a function that returns some Hiccup, it can't compile that automatically. It has to wait till the function returns to know what it is. That is, unless . . .

**The fix: ** The way to get Hiccup to compile something is with the hiccup.core/html macro. That's the macro that does the compilation and it will do it anywhere. So if you've got code like this:

(defn make-list [items]
  [:ul
    (for [i items]
      [:li i])])

(defn my-three-lists []
  [:div
    (make-list list1)
    (make-list list2)
    (make-list list3)])

You should wrap the Hiccup form in its own compiler, like this:

(defn make-list [items]
  (html
    [:ul
      (for [i items]
        [:li i])]))

For this little example, it probably won't make a noticeable difference. But it can be significant for larger documents.

Just to note: the Hiccup compiler can understand if and for forms, so there's no need to wrap them in the compiler. No hard either.

Autoterminating

Just a good thing to know about HTML.

Did you know that this is not legal HTML?

<script />

It's true. A script tag can't be self-closing.

There's all sort of silly rules in HTML like this. And then there's XML mode versus HTML mode. We are lucky: Hiccup does all of this for you, so you don't have to wade through the HTML spec(s!) looking for why something won't render in IE7.

The fix: hiccup.core/html takes a map of options as the first argument (it's optional). If you pass in a :mode option, it will set the correct HTML mode, which unfortunately are incompatible. There are three modes, :xml, :html, and :xhtml. The default is :xhtml.

Id/class DSL

Hiccup is a DSL. And it has its own sub DSL for HTML ids and classes. It's similar to CSS selectors.

Let's say you have a div like this:

[:div
  {:id "main-content"
   :class "blue-background green-border"}
  (h "Here's some content.")]

Well, Hiccup lets you make that shorter and easier to read.

The fix: Use the id/class DSL:

[:div#main-content.blue-background.green-border
  (h "Here's some content")]

Here's how it works. Every element has an optional id and zero or more classes. After the tag name (div here), you can put the id after a #. Then list your classes starting with a . each. Omit the # if there's no id. Ditto for the . if there's no class. Oh, and the id must come first. That will get converted to the id and class attributes you want. Also, these will conflict with attributes in the map, so choose one or the other, not both.

Generating Hiccup from HTML

Last thing, I promise!! Sometimes you have some HTML that someone gave you and you want to Hiccupify it so you can just stick it into your code. Manually doing that is kind of tedious. Luckily, there's a solution our there for you.

The fix: This page lists three options for outputting HTML from Hiccup. I have personally used Hiccup-bridge. It does a good job (and it even goes both ways). You call it like this:

lein hicv 2clj hello.html

That will output hicv/hello.clj in hiccup format. Pretty rocking when you need it.

Conclusion

Well, there you go. My Hiccup tips. Hiccup is pretty nice for templating. I recommend using it (or my future secure fork) in your web projects. If you'd like to learn more Hiccup and how to build web apps in Clojure, please check out [Lispcast Web Development in Clojure][webdev]. It's a video course teaching just that. All you need to know is Clojure and HTML.

You might also like

Announcing: LispCast Intro to clojure.test

Summary: The next course will be about clojure.test. Sign up to be notified when it is published.

Last week I mentioned my new course format, and I also teased at more announcements. Well, it's a course on clojure.test, the Clojure testing library that comes built in with Clojure.

I chose clojure.test as my next topic for a number of reasons. The main reason is that I think it's a good idea to begin with the fundamentals. I have a long list of topics, and testing was as good as any. It's also a video that opens doors to other topics, including testing using Midje, test.check, and simulation testing.

The course is called LispCast Intro to clojure.test. clojure.test is not a big library, but it's important to know. This course will teach you how to use the library and conventions around testing that might not be so obvious. For instance, how to name your testing namespace.

The course is built in the new format, and it's shorter than my previous courses. It's common for someone to tell me how much they like my courses. My first question is always "Did you finish them?". And it disturbs me how many people say "no". They like the course but they don't finish. So I'm doing smaller courses that are easier to fit into your day and finish. I expect to make more, smaller courses from now on. And Intro to clojure.test will be the first.

And now that that announcement is done, I must tease you with just one more announcement coming later this week. If you don't want to miss it, sign up for the mailing list below. You'll be the first one to know when clojure.test is coming out and what that cliffhanger announcement is.

You might also like

New Course Format

Summary: LispCast video courses have a new, interactive format. It's easier for me to make courses (read: more, faster) and it's a better experience for learners.

I've released 3 Clojure LispCast video courses. They've been selling okay (many thanks to my beautiful buyers and other supporters!), but I need more videos to bring it to a full time wage. After it took 9 months to do the core.async videos1, I decided to take a step back and optimize my process.

The first thing I wanted to do was to be able to generate the videos programmatically. Editing video takes a long time, and I knew that most of what I did during editing was automatable. That would eliminate hours of work per hour of video.

I began coding up some routines to compose videos functionally (inspired by the functional animation work by Conal Elliott). It worked really well. I could code up simple animations, concatenate videos, and rerender a preview very quickly. This combined with the Emacs Lisp scripts I have for automatically recording the "typing" portions of the videos, I was ready to code up the video.

But I eventually scrapped the idea. Nothing wrong with the idea, but I found something better. Nola Stowe suggested I make the video course viewable in a browser. That means I have HTML and Javascript. Not only does it let me have a bit of interactivity (such as pausing at the right place automatically), it also enhances the experience a lot. Table of contents, links, smaller download, etc. So I got to work on an in-browser course.

I'm working on the next LispCast course, in the new format. It's already way faster to make, and the viewer experience is amazing. It combines video, interactive exercises, animations, and more into one package. I can't wait to show the world. I've got a lot of great things to announce soon, so sign up below to get updates as they come out.

You might also like


  1. It took 9 months calendar time. It's a part time endeavor to begin with, and I had a few false starts and a few breaks. But mostly it's just a labor-intensive process.

The Parts of Ring

Summary: Ring, the Clojure Web library, defines three main concepts that you use to construct web applications.

Ring is the center of the Clojure web universe. It's not the only option in town, but the other options refer to Ring to say how they are different. Understanding Ring will help you learn any other web system in Clojure.

Ring has three main concepts that work together to build a web application.

  1. Adapters
  2. Handlers
  3. Middleware

Adapters

I like to think of Ring Adapters as plug adapters. When you go to a different continent, you often have to adapt the holes in the electical outlet to fit your cords. Ring Adapters let you convert different web server implementations into a standard Ring Request/Response format. That way, all of your code is standardized to the Ring format. Your code can travel into any kind of server as long as an adapter exists.

There are Ring Adapters for many existing servers.

And more.

Handlers

Handlers do the work of your application. They are like the computer. They are just Clojure functions. HTTP is basically a request/response protocol that maps well to functions, which are just a protocol from argument to return value. Handlers take a Ring Request and return a Ring Response. They should do whatever logic is necessary for your application.

Middleware

Middleware are the voltage converters. Here in North America, wall sockets run at 120 volts, which is different from almost everywhere. In order to run an appliance from elsewhere, you not only need to adapt the socket, you also need to transform the current to a compatible voltage. Middleware are often used to convert the incoming request in some standard way. For instance, there is middleware to parse a JSON body into a Clojure map and store it away in the request.

The transformer also "cleans up" the current. Voltage spikes are evened out so they never get to the computer. Middleware can similarly protect a handler by making sure the browser is logged in.

The analogy kind of breaks down, because middleware can do work (like the computer). Middleware are the hardest part of the Ring idea. They're not hard because the concept is hard. They're hard because they require design decisions. If all you had were Adapters and Handlers, you wouldn't have to think about where to put your logic. It would all go in the Handlers.

But there would be a lot of duplicated logic in your handlers. Authentication, routing, content-type switching, all of these things are done the same way over and over. It's the perfect problem for a little higher order programming. That's essentially what Middleware is.

Ring Middleware are functions that take a Handler and return a new Handler. Since Handlers are functions, Middleware are higher-order functions. The transformer on your computer's power cord takes a machine that requires a certain current and turns it into a machine that takes a different current. Middleware are used to do all sorts of things.

So, for instance, there's a Middleware called Prone that captures exceptions in the Handler and displays them in a nice format. Prone is a function that takes a Handler and returns a new Handler that catches exceptions and returns a different Ring Response in that case. Or you have Middleware that handle session cookies. The Middleware take a Handler and return a new Handler that understands sessions.

My recommendation for what to put in Middleware versus what to put in Handlers is simplest to explain with a graph.

Along the x-axis, we have logic that ranges from HTTP logic (handling header values, query params, etc.) to business logic (which bank account to withdraw from). Along the y-axis, we have how unique the logic is, ranging from highly duplicated to custom. These are the two axes I use to figure out whether it should be in the Handler or the Middleware.

The clear cases are easy. In the upper right corner (red dot), where it's custom business logic, it's definitely in the Handler. In the lower left (blue dot), where it's duplicated HTTP logic, I prefer Middleware. The hard part is in the middle. Somewhere between those two, there's a fine line where a case-by-case decision is required.

Conclusions

Ring is great because it requires so few concepts to capture so much of HTTP. But it's not everything. Standard Ring does not support WebSockets, for instance. Small adaptations are necessary. In general, I think this is a great abstraction. And Ring is so central to Clojure on the Web, it's important to know.

If you want to learn more about Ring and how to construct web applications in Clojure, you should check out LispCast Web Development in Clojure. It's a video course designed to guide you through the major libraries used for web development. You'll learn how to build Clojure web applications from existing and custom parts. You build Middleware to make your application adapt to browser limitations. And if you sign up below, you'll get a handy Ring Spec reference sheet, which specifies the Request and Response formats.

You might also like

Object-Oriented Programming is the Dual of Functional Programming

Summary: Object-Oriented Programming is often shown in contrast to Functional Programming. But they are so exactly opposite that they are duals, and so equivalent in important ways. Which one to use should be left up to the programmer, as is done in Clojure and Javascript.

Let's take a quick look at programming from an interesting perspective. Let's say that programs are divided into code and data. 1 These are the two main axes: structuring code and structuring data.

Now, let's design a language. First decisions: which axis is primary, which is secondary?

Style Data Code
OOP Primary Secondary
FP Secondary Primary

In an OOP-style approach, we have a pointer to an object which is the data. And the data also tells you where the code is to access it (methods in the vtable). An FP-style approach will make functions (code) primary, with data referred to by the closures (the captured lexical environment).

I'm positive I'm not the first person to remark on this, but I think it's pretty cool that they are duals of each other. A simple transformation will switch one in the table with the other.

Perhaps the next obvious question is "which one is better?". Many arguments about OOP vs FP focus on this choice, about which axis should be primary. Because a compiler could easily transform between them, the decision is not quite so important as we might think at first. I think that a language should make both available and let the programmer choose. The programmer is then free to choose whichever best models the problem.

For instance, in Clojure, fns are closures, so they are really FP-style -- code meant to be executed which happens to refer to some data. But collections are data which refer to code which knows how to access the data. Both coexist quite cooperatively.

And Clojure gives you, the programmer, ways of expressing both styles. When you want to create some code to be executed, fn lets you define lexical closures. But sometimes you want to make a new data structure which acts like others. For instance, a new type of sequence. deftype lets you define data with interface and protocol implementations. I use both fn and deftype very often.

Interestingly, Javascript gives you these two options as well. function defines lexical closures, making code primary. But very often you define an object which contains (or refers to) data and secondary accessor functions. It's one of the nicer things about Javascript, included in Javascript, the Good Parts.

How does your language prioritize these two axes? Is there a way to choose which to use to best implement your design? If you'd like to learn Clojure, which does have both styles, you should check out LispCast Introduction to Clojure, a video course that teaches functional programming through Clojure with animations, exercises, and code screencasts.

Learn Functional Programming using Clojure with screencasts, visual aids, and interactive exercises
Learn more

You might also like


  1. I don't want to go down the code-is-data rabbit hole. Let's stick to one floor in the tower of languages model.