Structuring the Code

One nontrivial difference between Clojure and imperative languages is the way the code is structured. In imperative style, it’s a common pattern to declare a shared mutable variable and modify it by passing it different functions. Each time we access the memory location, we see the result of the code that previously worked with it. For example, if we have a list of integers and we wish to square each one and then print the even ones, the following Python code would be perfectly valid:

 l = range(1, 6)
 
 for​ i, val ​in​ enumerate(l) :
  l[i] = val * val
 
 for​ i ​in​ l :
 if​ i % 2 == 0 :
 print​ i

In Clojure this interaction has to be made explicit. Instead of creating a shared memory location and then having ...

Get Web Development with Clojure, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.