from inner functions. But built on Clojure’s dynamic Var binding is a more active

mode of error handling, where handlers are pushed into inner functions. In section

11.10, we mentioned that the binding form is used to create thread-local bindings,

but its utility isn’t limited to this use case. In its purest form, dynamic scope is a struc-

tured form of a side effect (Steele 1978). You can use it to push Vars down a call stack

from the outer layers of a function nesting into the inner layers, a technique that we’ll

demonstrate next.

DYNAMIC TREE TRAVERSAL

In section 8.4, we built a simple tree structure for a domain model where each node

was of this form:

{:tag <node form>, :attrs {}, :content [<nodes>]}

As it turns out, the traversal of a tree built from such nodes is straightforward using

mundane recursion, as shown:

(defn traverse [node f]

(when node

(f node)

(doseq [child (:content node)]

(traverse child f))))

For each node in the tree, the function f is called with the node itself, and then each

of the node’s children is traversed in turn. Observe how traverse works for a single

root node:

(traverse {:tag :flower :attrs {:name "Tanpopo"} :content []}

println)

; {:tag :flower, :attrs {:name Tanpopo}, :content []}

But it’s much more interesting if we traverse trees larger than a single node. There-

fore, we can build a quick tree from an XML representation using Clojure’s clojure.

xml/parse function:

(use '[clojure.xml :as xml])

(def DB

(-> "<zoo>

<pongo>

<animal>orangutan</animal>

Download from Wow! eBook <www.wowebook.com>

Error handling and debugging

307

</pongo>

<panthera>

<animal>Spot</animal>

<animal>lion</animal>

<animal>Lopshire</animal>

</panthera>

</zoo>"

.getBytes

(java.io.ByteArrayInputStream.)

xml/parse))

The DB Var contains an animal listing for a small zoo. Note that two of the animals

listed have the elements Spot and Lopshire; both are seemingly out of order for a

zoo. Therefore, we can write a function to handle these nefarious intruders.

Listing 13.8 Handling nefarious tree nodes with exceptions

(defn ^{:dynamic true} handle-weird-animal

[{[name] :content}]

Define error handler

(throw (Exception. (str name " must be 'dealt with'"))))

(defmulti visit :tag)

(defmethod visit :animal [{[name] :content :as animal}]

(case name

"Spot" (handle-weird-animal animal)

"Lopshire" (handle-weird-animal animal)

(println name)))

(defmethod visit :default [node] nil)

The multimethod visit can be used as the input function to the traverse function

and will only trigger when a node with the :tag attribute of :animal is encountered.

When the method triggered on :animal is executed, the node :content is destruc-

tured and checked against the offending Spot and Lopshire values. When found, the

devious node is then passed along to an error handler handle-weird-animal for

reporting.5 By default, the error handler throws an exception. This model of error

handling is the inside-out model of exceptions. But handling errors in this way stops

the processing:

(traverse DB visit)

; orangutan

; java.lang.Exception: Spot must be 'dealt with'

We’ve managed to identify Spot, but the equally repugnant Lopshire escapes our

grasp. It’d be nice to instead use a different version of handle-weird-animal that

allows us to both identify and deal with every such weird creature. We could pass

handle-weird-animal along as an argument to be used as an error continuation,6 but

5

The metadata {:dynamic true} attached to handle-weird-animal isn’t really used in Clojure 1.2, but it

may be required in future versions of Clojure starting with 1.3 to allow the dynamic binding we’re about to

demonstrate.

6

See section 7.3 for more information on continuation-passing style.

Download from Wow! eBook <www.wowebook.com>

308

CHAPTER 13 Clojure changes the way you think

that pollutes the argument list of every function along the way. Likewise, we could

inject catch blocks at a point further down the call chain, say within visit, but we

might not be able to change the source, and if we could it makes for a more insidious

pollution. Instead, using a dynamic binding is a perfect solution, because it allows us

to attach specific error handlers at any depth in the stack according to their appropri-

ate context:

(defmulti handle-weird (fn [{[name] :content}] name))

(defmethod handle-weird "Spot" [_]

(println "Transporting Spot to the circus."))

(defmethod handle-weird "Lopshire" [_]

(println "Signing Lopshire to a book deal."))

(binding [handle-weird-animal handle-weird]

(traverse DB visit))

; orangutan

; Transporting Spot to the circus.

; lion

; Signing Lopshire to a book deal.

As you might expect, this approach works across threads to allow for thread-specific

handlers:

(def _ (future

(binding [handle-weird-animal #(println (:content %))]

(traverse DB visit))))

; orangutan

; [Spot]

; lion

; [Lopshire]

What we’ve outlined here is a simplistic model for a grander error-handling scheme.

Using dynamic scope via binding is the preferred way to handle recoverable errors in

a context-sensitive manner.

13.4.2 Debugging

The natural progression of debugging techniques as discovered by a newcomer to

Clojure follows a fairly standard progression:

1

(println)

2

A macro to make (println) inclusion simpler

3

Some variation on debugging as discussed in this section

4

IDEs, monitoring, and profiling tools

Many Clojure programmers stay at step 1, because it’s simple to understand and also

highly useful, but there are better ways. After all, you’re dealing with Clojure—a

highly dynamic programming environment. Observe the following function:

(defn div [n d] (int (/ n d)))

Download from Wow! eBook <www.wowebook.com>

Error handling and debugging

309

The function div simply divides two numbers and returns an integer value. You can

break div in a number of ways, but the most obvious is to call it with zero as the

denominator: (div 10 0). Such an example would likely not give you cause for con-

cern should it fail, because the conditions under which it fails are fairly limited, well

known, and easily identified. But not all errors are this simple, and the use of println

is fairly limited. Instead, a better tool would likely be a generic breakpoint7 that could

be inserted at will and used to provide a debug console for the current valid execution

context. Imagine it would work as follows:

(defn div [n d] (break) (int (/ n d)))

(div 10 0)

debug=>

At this prompt, you can query the current lexical environment, experiment with dif-

ferent code, and then resume the previous execution as before. As it turns out, such a

tool is within your grasp.

A BREAKPOINT MACRO

We hope that by the end of this section, you’ll understand that Lisps in general, and

Clojure in particular, provide an environment where the whole of the language truly is

“always available” (Graham 1993). First of all, an interesting fact to note is that the

Clojure REPL is available and extensible via the Clojure REPL itself, via the clojure.

main/repl function. By accessing the REPL implementation directly, you can custom-

ize it as you see fit for application-specific tasks.

Typing (clojure.main/repl) at the REPL seemingly does nothing, but rest

assured you’ve started a sub-REPL. What use is this? To start, the repl function takes a

number of named parameters, each used to customize the launched REPL in different

ways. We’ll utilize three such hooks—:prompt, :eval, and :read—to fulfill a break-

point functionality.

OVERRIDING THE REPL’S READER

The repl function’s :read hook takes a function of two arguments: the first corre-

sponding to a desired display prompt, and the second to a desired exit form. We want

the debug console to provide convenience functions—we’d like it to show all of the

available lexical bindings and also to resume execution. It also needs to be able to

read valid Clojure forms, but because that’s too complex a task, we’ll instead farm that

functionality out to Clojure’s default REPL reader.

Listing 13.9 A modest debug console reader

(defn readr [prompt exit-code]

(let [input (clojure.main/repl-read prompt exit-code)]

(if (= input ::tl)

exit-code

input)))

7 The code in this section is based on debug-repl created by the amazing George Jahad, extended by Alex

Osborne, and integrated into Swank-Clojure by Hugo Duncan.

Download from Wow! eBook <www.wowebook.com>

310

CHAPTER 13 Clojure changes the way you think

We can start testing the reader immediately:

(readr #(print "invisible=> ") ::exit)

[1 2 3]

;=> [1 2 3]

(readr #(print "invisible=> ") ::exit)

::tl

;=> :user/exit

The prompt that we specified was of course not printed, and typing ::tl at the

prompt did nothing because the readr function isn’t yet provided to the repl as its

:read hook. But before we do that, we need to provide a function for the :eval hook.

Needless to say, this is a more complex task.

OVERRIDING THE REPL’S EVALUATOR

In order to evaluate things in context, we first need a function cab to garner the bind-

ings in the current context. Fortunately for us, Clojure macros provide an implicit

argument &env that’s a map of the local bindings available at macro-expansion time.

We can then extract from &env the values associated with the bindings and zip them

up with their names into a map for the local context, as shown next.

Listing 13.10 Creating a map of the local context using &env

(defmacro local-context []

(let [symbols (keys &env)]

(zipmap (map (fn [sym] `(quote ~sym)) symbols) symbols)))

(local-context)

;=> {}

(let [a 1, b 2, c 3]

(let [b 200]

(local-context)))

;=> {a 1, b 200, c 3}

The local-context macro provides a map to the most immediate lexical bindings,

which is what we want. But what we really want to do is to provide a way to evaluate

expressions with this contextual bindings map. Wouldn’t you know it, the contextual-

eval function from section 8.1 fits the bill. So now that we have the bulk of the imple-

mentation complete, we’ll now hook into the repl function to provide a breakpoint

facility.

PUTTING IT ALL TOGETHER

The hard parts are done, so to wire them into a usable debugging console is relatively

easy, as shown next.

Listing 13.11 The implementation of a breakpoint macro

(defmacro break []

`(clojure.main/repl

:prompt #(print "debug=> ")

:read readr

:eval (partial contextual-eval (local-context))))

Download from Wow! eBook <www.wowebook.com>

Error handling and debugging

311

Using this macro, we can now debug the original div function:

(defn div [n d] (break) (int (/ n d)))

(div 10 0)

debug=>

Querying locals to find the “problem” is simple:

debug=> n

;=> 10

debug=> d

;=> 0

debug=> (local-context)

;=> {div #<user$div__155 user$div__155@51e67ac>, n 10, d 0}

debug=> ::tl

; java.lang.ArithmeticException: Divide by zero

So there’s the problem! We passed in a zero as the denominator. We should fix that.

MULTIPLE BREAKPOINTS AND BREAKPOINTS IN MACROS

What would be the point if you couldn’t set multiple breakpoints? Fortunately, you

can, as we show in the following listing.

Listing 13.12 Using multiple breakpoints in function keys-apply

(defn keys-apply [f ks m]

(break)

(let [only (select-keys m ks)]

(break)

(zipmap (keys only) (map f (vals only)))))

(keys-apply inc [:a :b] {:a 1, :b 2, :c 3})

debug=> only

; java.lang.Exception: Unable to resolve symbol: only in this context

debug=> ks

;=> [:a :b]

debug=> m

;=> {:a 1, :b 2, :c 3}

debug=> ::tl

debug=> only

;=> {:b 2, :a 1}

debug=> ::tl

;=> {:a 2, :b 3}

And finally, you can use breakpoints within the body of a macro (in its expansion, not

its logic), as shown next.

Listing 13.13 Using a breakpoint in a macro awhen

(defmacro awhen [expr & body]

(break)

`(let [~'it ~expr]

(if ~'it

(do (break) ~@body))))

(awhen [1 2 3] (it 2))

Download from Wow! eBook <www.wowebook.com>

312

CHAPTER 13 Clojure changes the way you think

debug=> it

; java.lang.Exception: Unable to resolve symbol: it in this context

debug=> expr

;=> [1 2 3]

debug=> body

;=> ((it 2))

debug=> ::tl

debug=> it

;=> [1 2 3]

debug=> (it 1)

;=> 2

debug=> ::tl

;=> 3

There’s much room for improvement, but we believe that the point has been made.

Having access to the underpinnings of the language allows you to create a powerful

debugging environment with little code. We’ve run out of ideas by now, so we’ll say

our credo only once more, and we hope by now you believe us.

Clojure changes the way that you think.

13.5

Fare thee well

This book possess many lacunae, but it’s this way by design. In many cases, we’ve

skipped approaches to solving problems via a certain route to avoid presenting non-

idiomatic code. In many examples, we’ve left exposed wiring. For example, the

defcontract macro requires that you partially apply the contract to the function

under constraint instead of providing a comprehensive contract overlay façade. It was

our goal to leave wiring exposed because exposed wiring can be explored, tampered

with, and ultimately enhanced—which we hope you’ll find the motivation to do.

We’ve worked hard to provide a vast array of relevant references should you choose

to further enhance your understanding of the workings and motivations for Clojure.

But it’s likely that we’ve missed some excellent resources, and we hope that you

instead are able to uncover them in time. Finally, this wasn’t a survey of Clojure, and

many of the functions available to you weren’t used in this book. We provide some

pointers in the resource list, but there’s no way that we could do justice to the librar-

ies and applications mentioned and those unmentioned. We implore you to look

deeper into the functionality of not only Clojure, but the rich ecology of libraries and

applications that have sprung up in its relatively short life span.

Thank you for taking the time to read this book; we hope it was as much a pleasure

to read as it was for us to write. Likewise, we hope that you’ll continue your journey

with Clojure. Should you choose to diverge from this path, then we hope that some of

what you’ve learned has helped you to view the art of programming in a new light.

Clojure is an opinionated language, but it and most of its community believe that

these opinions can work to enhance the overall state of affairs in our software indus-

try. The onus is on us to make our software robust, performant, and extensible. We

believe that the path toward these goals lies with Clojure.

Do you?

—FOGUS AND HOUSER 2010

Download from Wow! eBook <www.wowebook.com>

resources

Miscellaneous resources

Abadi, Martin, and Luca Cardelli. 1996. A Theory of Objects. New York: Springer. Although not a math-

ematical concept, object-oriented programming has obtained rigor with this gem.

Abelson, Harold, and Gerald Jay Sussman. 1988. Lisp: A Language for Stratified Design.” AI Memo

(MIT) 986.

———. 1996. Structure and Interpretation of Computer Programs. Cambridge, MA: MIT Press. There is no

better book for learning Scheme and the fine art of programming.

Abiteboul, Serge, Richard Hull, and Victor Vianu. 1995. Foundations of Databases. Boston: Addison-

Wesley. Clojure’s clojure.set namespace is actually modeled more on the named conjunctive

algebra, for which this book provides a great reference.

Armstrong, Joe. 2007. Programming Erlang. Raleigh, NC: Pragmatic Bookshelf.

———. 2007. “A History of Erlang.” Proceedings of the Third ACM SIGPLAN Conference on History of Pro-

gramming Languages.

Bagwell, Phil. 2001. Ideal Hash Trees. Technical report. Clojure’s persistent data structures owe a lot to

Phil Bagwell’s paper.

Baker, Henry. 1993. “Equal Rights for Functional Objects or, The More Things Change, The More

They Are the Same.” ACM SIGPLAN OOPS Messenger 4, no. 4.

Beck, Kent. 2002. Test Driven Development: By Example. Boston: Addison-Wesley.

Bloch, Joshua. 2008. Effective Java. Upper Saddle River, NJ: Addison-Wesley.

Boncz, Peter, Zukowski Marcin, and Niels Nes. 2005. “MonetDB/X100: Hyper-Pipelining Query 

Execution.” Proceedings of the CIDR Conference. This paper motivated the implementation of

chunked sequences.

Bratko, Ivan. 2000. PROLOG: Programming for Artificial Intelligence. New York: Addison Wesley.

Budd, Timothy. 1995. Multiparadigm Programming in Leda. Reading, MA: Addison-Wesley. This is an

expanded discussion of the complexities wrought from a mono-paradigm approach to software

development.

Clinger, William. 1998. “Proper Tail Recursion and Space Efficiency.” Proceedings of the ACM SIGPLAN

1998 Conference on Programming Language Design and Implementation.

Cormen, Thomas, Charles Leiserson, Ronald Rivest, and Clifford Stein. 2009. Introduction to Algo-

rithms. Cambridge, MA: MIT Press. This is a great reference on algorithmic complexity and Big-

O, and as an added bonus, you could use it to stop a charging rhinoceros.

313

Download from Wow! eBook <www.wowebook.com>

314

RESOURCES

Crockford, Douglas. 2008. JavaScript: The Good Parts. Yahoo Press.

Date, C.J. 2009. SQL and Relational Theory: How to Write Accurate SQL Code. Sebastopol, CA: O’Reilly.

Dijkstra, Edsger Wijbe. 1959. A Note on Two Problems in Connexion with Graphs.” Numerische Mathema-

tik 1, no. 1. You could change the h function in listing 7.9 to (defn dijkstra-estimate-cost

[step-cost-est sz y x] 0) to conform to the ideal presented in this paper.

Flanagan, David. 2006. JavaScript: The Definitive Guide. Sebastopol, CA: O’Reilly.

Forman, Ira, and Nate Forman. 2004. Java Reflection in Action. Greenwich, CT: Manning. Although reflec-

tion provides some meta-level manipulation, it’s quite apart from the notion of functions as data.

Friedl, Jeffrey. 1997. Mastering Regular Expressions. Sebastopol, CA: O’Reilly.

Friedman, Daniel, Mitchell Wand, and Christopher T. Haynes. 2001. Essentials of Programming Languages.

Cambridge, MA: MIT Press.

Gabriel, Richard, and Kent Pitman. 2001. “Technical Issues of Separation in Function Cells and Value

Cells.” This is a more thorough examination of the differences between Lisp-1 and Lisp-2.

Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. 1995. Design Patterns: Elements of

Reusable Object-Oriented Software. Reading, MA: Addison-Wesley.

Ghosh, Debasish. 2010. DSLs in Action. Greenwich, CT: Manning. There is a much finer level of distinc-

tion determining what constitutes whole cloth, including that between internal and external DSLs.

In this book, we focus on the classical Lisp model of internal DSLs, but DSLs in Action provides a sur-

vey of many DSL-creation techniques.

Glickstein, Bob. 1997. Writing GNU Emacs Extension s. Sebastopol, CA: O’Reilly.

Goetz, Brian. 2006. Java Concurrency in Practice. Upper Saddle River, NJ: Addison-Wesley. Why haven’t you

read this yet?

Goldberg, David. 1991. What Every Computer Scientist Should Know About Floating-Point Arithmetic.”

Computing Surveys (March).

Graham, Paul. 1993. On Lisp. Englewood Cliffs, NJ: Prentice Hall. Is there any book or any author more

influential to the current generation of dynamic programmers than Graham and On Lisp?

———. 1995. ANSI Common Lisp. Englewood Cliffs, NJ: Prentice Hall.

Gray, Jim, and Andreas Reuter. 1992. Transaction Processing: Concepts and Techniques. San Mateo, CA: Mor-

gan Kaufmann Publishers.

Halloway, Stuart. 2009. Clojure is a better Java than Java .” Presented at the Greater Atlanta Software

Symposium, Atlanta. The origin of the phrase “Java.next” most likely stems from this talk by 

Halloway.

Hart, Peter, Nils Nilsson, and Bertram Raphael. 1968. “A Formal Basis for the Heuristic Determination

of Minimum Cost Paths.” IEEE Transactions on Systems Science and Cybernetics In Systems Science and

Cybernetics 4, no. 2.

Hewitt, Carl, Peter Bishop, and Richard Steiger. 1973. A Universal Modular ACTOR Formalism for Arti-

ficial Intelligence .” Proceedings of the Third International Joint Conference on Artificial Intelligence.

Heinlein, Robert. 1966. The Moon Is a Harsh Mistress. New York: Putnam. We had considered offering an

implementation of Mike as an appendix, but we ran over our page count.

Herlihy, Maurice, and Nir Shavit. 2008. The Art of Multiprocessor Programming. Amsterdam; Boston:

Elsevier/Morgan Kaufmann.

Hickey, Rich. 2009. Are We There Yet?” Presented at JVM Languages Summit. This wonderful presenta-

tion made firm the popular view of Rich as Philosopher Programmer.

Hofstadter, Douglas. 1979. Gödel, Escher, Bach: An Eternal Golden Braid. New York: Basic Books. See the sec-

tions “Classes and Instances,” “The Prototype Principle,” and “The Splitting-off of Instances from

Classes” for more detail of the topics in section 9.2.

Download from Wow! eBook <www.wowebook.com>

RESOURCES

315

Hoyte, Doug. 2008. Let Over Lambda. Lulu.com. This is an amazing look into the mind-bending power of

Common Lisp macros that provided the motivation for the DSLs section of this book. It will blow

your mind—in a good way.

Hudak, Paul. 2000. The Haskell School of Expression: Learning Functional Programming Through Multimedia.

New York: Cambridge University Press.

Huet, Gerard. 1997. “Functional Pearl: The Zipper.” Journal of Functional Programming.

Hutton, Graham. 1999. “A Tutorial on the Universality and Expressiveness of fold.” Journal of Functional

Programming 9, no. 4.

Kahan, William, and Joseph Darcy. 1998. “How Java’s Floating-Point Hurts Everyone Everywhere.” Pre-

sented at the ACM Workshop on Java for High-Performance Network Computing. This paper pro-

vides more information on the cyclopian nightmares awaiting you in Java floating point.

Keene, Sonya. 1989. Object-Oriented Programming in Common Lisp: A Programmer’s Guide to CLOS. Boston:

Addison-Wesley. The best book on CLOS ever written.

Knuth, Donald. 1997. The Art of Computer Programming: Volume 1 - Fundamental Algorithms. Reading, MA:

Addison-Wesley. This book goes into exquisite detail about the primary characteristics of FIFO

queues and is highly recommended reading.

———. 1998. The Art of Computer Programming, Vol. 3: Sorting and Searching. Reading, MA: Addison-Wesley.

Running quick-sort on a sorted sequence is an O(n2) operation, which for our implementation in

chapter 6 completely defeats its laziness.

Koenig, Dierk, Andrew Glover, Paul King, Guilaume LaForge, and Jon Skeet. 2007. Groovy in Action.

Greenwich, CT: Manning.

Kuki, Hirondo, and William James Cody. 1973. “A Statistical Study of the Accuracy of Floating Point

Number Systems.” Communications of the ACM 1973 16, no. 4.

Laddad, Ramnivas. 2003. AspectJ in Action: Practical Aspect-Oriented Programming. Greenwich, CT: 

Manning. We do not do justice to the notion of aspects—so read this instead.

Martin, Robert. 2002. Agile Software Development: Principles, Patterns, and Practices. Upper Saddle River, NJ:

Prentice Hall.

McCarthy, John. 1960. “Recursive Functions of Symbolic Expressions and Their Computation by

Machine, Part I.” Communications of the ACM. This is the essay that started it all.

———. 1962. LISP 1.5 Programmer’s Manual. Cambridge, MA: MIT Press. Lisp had an array type at least as

early as 1962. Sadly, this fact is little known.

McConnell, Steve. 2004. Code Complete: A Practical Handbook of Software Construction. Redmond, WA: 

Microsoft Press.

Meyer, Bertrand. 1991. Eiffel: The Language. New York: Prentice Hall. The programming language Eiffel

relies heavily on contract-based programming methodologies, a cornerstone element of Fogus’s

philosophy of Apperception-Driven Development.

———. 2000. Object-Oriented Software Construction. Upper Saddle River, NJ: Prentice Hall.

Michie, Donald. 1968. Memo Functions and Machine Learning.” Nature 218.

Mooers, Calvin, and Peter Deutsch. 1965. “TRAC, A Text-Handling Language.”

Moseley, Ben, and Peter Marks. 2006. “Out of the Tar Pit.” Presented at SPA2006.

Mozgovoy, Maxim. 2009. Algorithms, Languages, Automata, and Compilers: A Practical Approach. Sudbury,

MA: Jones and Bartlett Publishers.

Noble, James, and Brian Foote. 2003. “Attack of the Clones.” Proceedings of the 2002 Conference on Pattern

Languages of Programs 13. The clone function is inspired by this paper.

Norvig, Peter. 1991. Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp. San Fran-

cisco: Morgan Kaufman Publishers.

Download from Wow! eBook <www.wowebook.com>

316

RESOURCES

Odersky, Martin, Lex Spoon, and Bill Venners. 2008. Programming in Scala: A Comprehensive Step-by-step

Guide. Mountain View, CA: Artima.

Okasaki, Chris. 1996. The Role of Lazy Evaluation in Amortized Data Structures.” Presented at the

International Conference on Functional Programming. This is a much more thorough discussion

of incremental vs. monolithic computation.

———. 1999. Purely Functional Datastructures. Cambridge University Press. Chris Okasaki to the rescue

again! Clojure’s persistent queue implementation is based on Okasaki’s batched queue from this

seminal work.

Olsen, Russ. 2007. Design Patterns in Ruby . Upper Saddle River, NJ: Addison-Wesley

Papadimitriou, Christos. 1986. Theory of Database Concurrency Control. New York: Computer Science 

Press, Inc.

Pierce, Benjamin. 2002. Types and Programming Languages. Cambridge, MA: MIT Press. Fun fact: Repre-

senting numbers using lambda calculus is known as church encoding. The church-encoded number

9 would be represented as (fn [f] (fn [x] (f (f (f (f (f (f (f (f (f x))))))))))) in 

Clojure.

Raymond, Eric. 2003. The Art of Unix Programming. Reading, MA: Addison-Wesley Professional.

Rosenberg, Doug, Mark Collins-Cope, and Matt Stephens. 2005. Agile Development with ICONIX Process:

People, Process, and Pragmatism. Berkeley, CA: Apress.

Skeel, Robert. 1992. Roundoff Error and the Patriot Missile.” SIAM News 25, no. 4: 11.

Steele, Guy L. 1977. Lambda: the Ultimate GOTO.” ACM Conference Proceedings.

———. 1990. Common LISP: The Language. Bedford, MA: Digital Press. This is a very witty book in addition

to being packed with information.

Steele, Guy L., and Gerald Sussman. 1978. “The Art of the Interpreter.” AI Memo (MIT) 453.

Stewart, Ian. 1995. Concepts of Modern Mathematics. New York: Dover. These Dover math books are often

true gems. It would be great to see an adventurous publisher print a similar series revolving around

C.S.-relevant topics—monads, category theory, lambda calculus, and so on.

Sussman, Gerald, and Guy L. Steele. 1975. “Scheme: An Interpreter for the Extended Lambda Calculus.”

Higher-Order and Symbolic Computation 11, no. 4. This is a discussion of Scheme’s early implementa-

tion of lexical closures.

Symbolics Inc. 1986. Reference Guide to Symbolics Common Lisp: Language Concepts. Symbolics Release 7 Doc-

ument Set.

Thompson, Simon. 1999. Haskell: The Craft of Functional Programming. Reading, MA: Addison-Wesley.

Ullman, Jeffrey. 1988. Principles of Database & Knowledge-Base Systems Vol. 1: Classical Database Systems.

Rockville, MD: Computer Science Press.

Ungar, David, and Randal Smith. 1987. SELF: The power of simplicity.” Presented at the Conference on

Object-Oriented Programming Systems, Languages, and Applications (OOPSLA), Orlando. The

Self programming language is likely the greatest influence on prototypal inheritance.

Van Roy, Peter, and Seif Haridi. 2004. Concepts, Techniques, and Models of Computer Programming.

Cambridge, MA: MIT Press.

Wadler, Philip. 1989. “Theorems for Free!” Presented at the fourth International Conference on Func-

tional Programming and Computer Architecture.

Wampler, Dean, and Alex Payne. 2009. Programming Scala. Sebastopol, CA: O’Reilly.

Download from Wow! eBook <www.wowebook.com>

RESOURCES

317

Whitehead, Alfred North. 1929. Process and Reality: An Essay in Cosmology. Cambridge University Press. For

a general overview of Whitehead, see The Wit And Wisdom of Alfred North Whitehead by A.H. Johnson

(Boston, Beacon Press, 1947).

Williams, Laurie. 2002. Pair Programming Illuminated. Boston: Addison-Wesley Professional. The limita-

tions of the book format only shadow the idealistic model of pair programming.

Online resources

Braithwaite, Reginald. 2007. “Why Why Functional Programming Matters Matters.” http://mng.bz/

2pZP. This column discusses a language-level separation of concerns.

Clementson, Bill. 2008. “Clojure could be to Concurrency-Oriented Programming what Java was to

OOP.” http://bc.tech.coop/blog/081201.html. A much deeper discussion concerning Erlang actors and Clojure agents.

Dekorte, Steve. Io . http://iolanguage.com.

Fogus, Michael. Lithp. http://github.com/fogus/lithp.

Fowler, Martin. 2005. “Fluent Interface.” http://mng.bz/e2r5.

———. 2007. “Mocks Aren’t Stubs.” http://mng.bz/mq95.

Graham, Paul. Arc. www.paulgraham.com/arc.html.

———. 2001. “What Made Lisp Different.” www.paulgraham.com/diff.html. As Paul Graham states,

“The whole language always available” appears as a theme throughout this book and as a finale in

section 13.5.

Houser, Chris. error-kit API . http://mng.bz/07FF. The clojure.contrib.error-kit namespace contains an open error system similar to CL conditions that don’t require recompilation when defining new

error types.

Krukow, Karl. 2009. “Understanding Clojure’s PersistentVector Implementation.” http://mng.bz/tmjv.

Lindholm, Tim, and Frank Yellin. 1999. Java Virtual Machine Specification. http://java.sun.com/docs/

books/jvms/.

Peter. 1998. Design Patterns in Dynamic Programming .” http://norvig.com/design-patterns/.

The section on design patterns was inspired by this presentation.

Tarver Mark. 2008. Functional Programming in Qi. www.lambdassociates.org/Book/page000.htm. Some programming languages perform partial application automatically when a function is 

supplied with fewer than the expected number of arguments. One such language is Qi.

———. 2009. “The Next Lisp: Back to the Future .” http://mng.bz/8wA9. The notion of Lisp as a programming language genotype is explored.

_why. Shoes. http://github.com/shoes/shoes.

Yegge, Steve. 2006. Execution in the Kingdom of Nouns . http://mng.bz/9ApS.

———. 2008. “The Universal Design Pattern.” http://mng.bz/6531. Like many programmers of our generation, we were in many ways inspired and influenced by Steve Yegge’s work—which is why we

asked him to write this book’s foreword.

Download from Wow! eBook <www.wowebook.com>

Download from Wow! eBook <www.wowebook.com>

index

Keywords and symbols

ACID 238

arglists 164

ad-hoc hierarchies 16, 70, 184,

argument 68

, 25, 158

186, 188, 304

arrays 74, 77, 79, 218–220

; 21

derivation hierarchy 186–187

amap 220

:as 40–41, 48–49, 182, 264

make-hierarchy 187

areduce 220

:exclude 41, 182, 258

adornment 278

multidimensional arrays 222

:import 42, 182

Agents 235, 240, 247, 249–255,

primitive arrays 218–219

:load 182

274

reference arrays 218

:only 182–183

agent-error 253

seq of an array 220

:post 133–134

await 249–250, 255

as-futures 263–265, 268

:pre 133–134

await-for 250–251

as-is 48

:private 181

queue 247, 251

aspects 135

:refer 41–42

restart-agent 253–254

assertions 173, 203

:refer-clojure 182, 258

send 248, 251–253

assert 134

:require 41, 182

send-off 248, 251–253

assoc 84–86, 191

:strs 49

serialize access 249

associative 66

:test 128

agile 202, 278

assoc-in 85

:use 41, 182–183

Ahead of Time Compilation

asum-sq 220, 278–280

naked :use 183

(AOT) 218, 227–228

asynchronous 240, 247

.. 37

alert 216

atomicity 238, 255

*read-eval* 270

algorithm 81

*warn-on-reflection* 278, 289

Atoms 235, 240, 255–257

alias 183

& 48, 50

compare-and-set! 255

anaphora 170–171, 211

autoboxing 288

anaphoric 173

auto-gensym 36, 165

A

anaphoric macros 170, 211

ancestors 186

A* pathfinding 149

and (logical) 114, 175

B

astar 149–154

anonymous inner classes 126

candidate paths 150

Apache Ant 181

backslash 73

cost-estimate function 150

Application Programming

bad-make-move 243

path-finding 149

Interface (API) 204, 293

beget 184

abstraction-oriented

public-facing API 181

benchmark 281

programming 16, 177,

apply 98, 127

best 72

184, 189, 206, 285–287

aquarium 69

best practices 303

abstractions 166, 188, 208, 227,

Arc (programming

best-case 81

284, 286

language) 170

best-first 149

accessors 202

awhen 170

BigDecimal 273–274

319

Download from Wow! eBook <www.wowebook.com>

320

INDEX

Big-O 77, 80–82

expressiveness of 5

compile 141, 213–214

algorithmic complexity 77

succinctness 72

compiler 117, 213, 218, 277,

asymptotic complexity 80–81,

clojure.contrib.json 168

288–291

124

clojure.contrib.repl-utils 52–53

Compiler.java 55

linear time 81

clojure.core 41, 179, 183, 271

compile-time 141, 231

logarithmic complexity 81

clojure.lang.IMeta 212

complement 128, 130

bind 47

clojure.lang.IPersistentStack 86

complexity 103, 238, 273

binding 47, 300

clojure.lang.PersistentQueue/

essential complexity 5

bit-xor 51

EMPTY 92

incidental complexities 164

blocks 29, 31

clojure.main/repl 309

composition 305

boilerplate 162, 164–165

clojure.set 40, 94, 96, 183, 294

concat 281

Booleans 279

clojure.string 41

concrescence 13

Boolean (Java class) 44, 83

clojure.test 128, 183, 300

concrete classes 16, 193, 195,

Boolean context 45

clojure.test/run-tests 128

208

bot object 139–140

clojure.xml 183, 262

concrete realization 286

bottom-up programming 298

clojure.xml/emit 305

concurrency 3, 14, 109, 234–

bound 272

clojure.xml/parse 263, 306

237, 245, 249, 258, 261

boxing 288

clojure.zip 183, 262

concurrent modification

autoboxing 288

clojure.zip/xml-zip 263

220, 259

unboxing 288

closures 17, 135–141, 197, 230,

concurrent modification

breakpoint 309–310

258, 305

errors 109

build-contract 174, 181

closing over parameters 137

concurrent

build-move 205–206

functions returning

programming 234–235,

byte 83

closures 136

248, 259

bytecode 141, 208, 210, 222

lexical closures 17

lost wakeup 236

bytes 279

passing closures as

model, distributed 248–249

functions 137

priority inversion 238

C

sharing closure context 138

vs. parallelism 235

code

cond 69, 162, 298

C (programming language) 8,

avoid repeating 196

confounding 281

21, 194, 198

is data 8, 11, 157–158, 161,

conj 86, 88, 90–92, 110, 196

calculations, precise 66

169

cons 32–33, 90

call stack 71

repetitive 47, 49

consistency 7–8, 238, 242, 261

callbacks 138, 266

coercion 277, 287–291

reporting problem 238

call-by-need 119

fifth rule of coercion 291

constant factor 81

canvas 51

first rule of coercion 288

constant time 281

capitalize 41

fourth rule of coercion 290

constructors 37, 55, 198, 204,

capturing group 74

second rule of coercion 290

212, 305

car 80, 90

third rule of coercion 290

contains? 89, 91, 95

case 147, 298

collect-bodies 173–174

continuation-passing style

chaining 202

collection 46, 280

(CPS) 148–149, 229, 304

change-message 209, 211

colon 23

accept function 148

char 83

columns 130

return continuation 148

character classes 73

commenting 21, 74

continuations 266, 307

characters, in a string 23

commits 248

continuation function 148

chars 279

Common Lisp (programming

continue 252, 254

chess 16, 202, 204–205, 241–242

language) 46, 72, 169, 298

contracts programming 173,

choose-move 242

cdr 80, 90

175–176, 299, 302–303, 312

chunked sequences 283

Common Lisp Object System

constraints 133, 173, 175,

clarity 7, 290

(CLOS) 187

301–302

clear 55

funcall 72

defcontract 312

clear-actions 253

Lisp-2 72

contrib 168, 271

Clojure

comp 127, 130

control structures 157, 159,

as opinionated language 312

comparator 95

161, 163

Clojure 1.3 271, 307

compare-and-swap 255

conversion specification 296

Download from Wow! eBook <www.wowebook.com>

INDEX

321

coordination 241, 269

subscriber patterns 129

dynamic scope 273–274, 306,

copies, defensive 226

Visitor pattern 304

308

counted 90

Design Patterns: Elements of

dynamic type systems 278, 287

counter-optimizations 280

Reusable Object-Oriented

count-tweet-text-task 263–264,

Software 303

E

266

destructuring 8, 47–48, 54, 57,

create-ns 179–180

133, 242

elegance 13, 45

crypto 69

associative destructuring 50

embedding 73

in function parameters 50

empowerment 6

D

nested 49

empty sequence 78–79

versus accessor methods 50

empty? 46

data structures, immutable

with a map 49

encapsulation 16–17, 305

108–109

with a vector 48

block-level encapsulation 17

database 236

determinacy 235

local encapsulation 17

deadlock 236, 238, 248–250,

directive 48–49, 52

namespace encapsulation 17

259, 267

directory structure 180–181

Enlive 168

deterministic 267

disappear 53

enumeration values 68

debug 309

dispatch 187

enumerator 78

debug console 309

display 212–213

env 310

debugging 293, 310, 312

dissoc 86, 190–191, 257

ephemeral 280

debug-repl 309

distributive 66

equality 68, 70–71, 109, 187

decimal 22

do 29, 163, 262

equality partitions 79, 102,

declarative 118, 293

doall 274

224

declare 173

documentation, viewing 53

equality semantics 79

def 27–28, 135, 137, 181, 271,

domain 166

Erlang (programming

273

domain-specific language

language) 248–249

actor 248

default-handler 209–210

(DSL) 10–11, 70, 164, 167,

Actor model 143

defformula 303–304

173, 204, 292–295, 298,

in-process versus distributed

definterface 227–229

301

concurrency models 248

defmacro 162, 181, 271

domain expertise 302

share-nothing 248

defmulti 188, 271

putting parentheses around

error handling 229, 254, 

defn 17, 27, 136, 164, 181, 271

the specification 295

306–308

defonce 271

unit conversion DSL 297

escaped 73

defprotocol 229

don’t panic 55

evaluation 32–33

defrecord 189–191, 199–200

doseq 7, 46, 55

contextual-eval 160–161, 310

defstruct 182, 190

dosync 242, 248

eval 159–161, 309–310

downfall of defstructs 190

dothreads! 240, 255

meta-circular 293

defunits-of 296–297

doto 38

exceptions 38, 55, 205, 229,

def-watched 165

double 63, 83

236, 252–254, 282, 293,

delay 113, 119, 121, 149, 287

double-array 222

306–307

delegate 215, 286

double-backslash 73

catch 38, 308

dependency injection (DI) 305

double-quotes 73

checked 229–230

deref 240, 255, 270, 272

doubles 65, 279

compile-time 55, 231

derive 186–187

do-until 162

ConcurrentModification-

descendants 186

drawing 53

Exception 259

design patterns 292, 303

duck typing 189

finally 172, 261

Abstract Factory pattern 304

dummy write 239

handling 229

Builder pattern 305

durability 238

java.lang.ClassCastException

chain of responsibility 305

DynaFrame.clj 213

231

Façade pattern 305

dynamic binding 287, 293, 306,

java.lang.Exception 230

Interpreter pattern 305

308

java.lang.NullPointer-

Observer pattern 303–304

binding 117, 271, 273, 290,

Exception 114

Prototype pattern 305

306, 308

java.lang.RuntimeException

Strategy pattern 304

bound-fn 274

230

Download from Wow! eBook <www.wowebook.com>

322

INDEX

exceptions (continued)

free variables 136

get-in 85–86

runtime 230

freedom to focus 5

getter 204

runtime vs. compile-time 230

frequencies 288

global hierarchy map 188

throw 38, 54–55, 231

Frink (programming

goal 247

expand-clause 11

language) 207, 294

Gödel, Escher, Bach: An Eternal

expansion 297

frustrating 246

Golden Braid 183

expected case 81

fully qualified 258, 270, 272

good-move 242

experimentation 179

fun 51

Graham, Paul 298, 309

expression problem 16

functional programming 12,

graphic 54

extend 15, 192, 195–197, 199

19, 108, 303

graphical user interface (GUI)

extend-protocol 192, 197

currying 127

138, 212, 214–216, 218

extend-type 192–193, 197

first-class functions 72, 126,

graphics context 53

Extensible Markup Language

130

greatest common

(XML) 168, 262–264,

functional composition 169,

denominator 144, 284

305–306

288, 294

green thread 254

higher-order functions 115,

Greenspun’s Tenth Rule 303,

F

129–131, 137, 142, 151,

305

154, 161, 173–174, 230,

Groovy (programming

Factor (programming

287, 304

language) 207

language) 12, 301

partial application 127, 305

factory methods 305

pure functions 5, 118, 

H

131–132, 149, 241, 298

fail 252, 254

referentially

false 44–45, 56

Halloway, Stuart 101, 208

transparent 131–132, 256,

evil-false 44

has 285

284

Fantom (programming

functions 25, 68

hash maps 99

language) 207

anonymous 28, 129, 138, 210

hash-map 80, 88, 97, 190

fence post errors 203

arity 26

Haskell (programming

filter 78, 119, 129, 138, 304

Calling Functions 25

language) 12, 47, 113,

find-doc 51

dangerous 75

118, 149, 161, 198, 285, 301

find-ns 179

function signatures 192

out of order execution 149

finite state machines 146

local 147

Template Haskell 161

first 78, 80, 90, 121, 127

multiple function bodies 50

typeclasses 198, 285

First In, First Out (FIFO) 91,

named arguments 132

heuristic 151

192

futures 235, 261–263, 265, 269

Hickey, Rich 4–5, 206

First In, Last Out (FILO) 192

as callbacks 262

hidden 52

first-class 12, 27, 128

future 149, 255, 274

hierarchy 205

fixed-size pool 252

future-cancel 264

history 246

FIXO 192–193, 195, 197

future-cancelled? 264

homoiconicity 12, 293

fixo-peek 199

future-done? 264

hooks 304, 309

fixo-push 193, 195, 200

hops 81

flexibility 9

G

host semantics 62

float 83, 291

Hoyte, Doug 294

floating point 22, 62, 65–67

Gang of Four 303

hyphens 181

overflow 83

garbage collection 207, 280,

rounding error 64

283

I

underflow 64, 83

gcd 145

floats 279

gen-class 38, 212, 214–215,

I/O 239, 249, 252

fluent builder 202–203

218, 233, 304

idempotent 239, 255–256

FluentMove 204–205

generalized tail-call

identical? 70–71

fn 26, 28, 82, 135–136, 146, 164

optimization 143–144, 149

identifiers 70

for 7, 51

generic 46

identity 3, 13–14, 71, 202, 211,

force 113, 119, 121

genotype 9

227, 235, 247, 254

forever 68

gensym 169

IDEs 308

form 24

get 84, 88, 94, 98

idiom 190

Download from Wow! eBook <www.wowebook.com>

INDEX

323

idiomatic 34, 36, 46, 62, 82, 87,

into-array 218–219, 222

java.lang.Thread 255

98, 114, 154, 158, 169, 179,

ints 279

Java.next 208

198, 277, 280, 298

invariants 203, 246

Java.next Mantra 208

if 31, 114, 162

inversion of control 164

java.util.ArrayList 79

if-let 120, 171

invoke 214

java.util.Collection 225

image 51, 56

Io (programming

java.util.Collections/sort 223

immutability 7, 14, 30, 77–78,

language) 185

java.util.Comparator 222–223

86, 91, 93, 100, 107–109,

Ioke (programming

java.util.concurrent 258, 261

136, 143, 202, 224, 248, 280

language) 207

java.util.concurrent

imperative programming 14,

isa? 186–187

FutureTask 224

30, 108

ISeq 121

java.util.concurrent.atomic.

implementation details 182

ISeqable 200

AtomicInteger 136, 256

implicit do 30

ISliceable 228–229

java.util.concurrent.Blocking-

inc 243

isolation 238

Queue 91

inconsistency 245

iteration 46, 305

java.util.concurrent.Callable 

index numbers 47

iterator 78, 88

222

infinite lazy range 68

java.util.concurrent.locks 260

infinite loop 46

J

java.util.concurrent.locks.

infinite sequence 113, 118, 283

ReentrantLock 260

infix notation 25

Jahad, George 160

java.util.concurrent.locks.

inheritance 5, 183, 185–186

Java 37, 208, 290

ReentrantReadWriteLock

differential 185

Java (programming

261

implementation

language) 4, 6, 8, 16, 18,

java.util.List 15, 79, 223, 225

inheritance 196

21, 32, 36, 38, 67, 91, 108–

java.util.Observable 304

interface inheritance 16

109, 129, 179, 192, 194,

java.util.RandomAccess 48

prototype chain 184, 187

198, 207, 209, 211, 215,

java.util.regex.Matcher 48, 75

prototype maps 183, 186

java.util.regex.Pattern 73

inherited behaviors 186

224, 235, 255, 260, 290

javadoc 53, 73

init 55

Java 7 126

JavaScript (programming

init-proxy 212

Java Collections

language) 16, 135, 141, 184

in-process programming

Framework 224, 226

javax.swing.JFrame 212

model 249

Java libraries 52

Jess (programming

instance 55, 71

polymorphic print

language) 207

int 83, 146

facility 204–205

Joswig, Ranier 295

integers 22

variadic constructor 222

joy.gui.DynaFrame 212

overflow 64

Java Virtual Machine (JVM) 4,

JRuby (programming

interactive command

6, 36, 62, 65, 144, 146,

language) 207

prompt 51

207–208, 220, 229, 234,

just-in-time (JIT) 207

interfaces 8, 16, 192–193, 195,

251, 280

juxt 188

200, 224, 285

HotSpot 207

Jython (programming

intern 179–180, 270, 272

java.awt 52

language) 207

internal reduce 280

java.awt.Container 212, 215

interop 73

java.awt.Frame 52

interoperability 24, 62, 196,

java.io.FilterOutputStream 211

K

200, 208, 218, 222, 224,

java.io.OutputStream 211

227, 277, 304

java.lang 42, 179

kapow 143

accessing Java instance

java.lang.Iterable 225

keep-indexed 102

members 37

java.lang.Math/round 291

key 49, 80, 88

accessing static class

java.lang.Object 128, 205, 220,

keys-apply 131–132

members 36

279

keyword arguments 278

creating Java class

java.lang.Runnable 222

keywords 23, 68–70, 241

instances 36

java.lang.StackOverflowError 

plumbing, separating from

setting Java instance

142, 230

domain 69

properties 37

java.lang.String 15

qualified 69

interpreted 298

java.lang.String/format 222

ubiquity of 75

into 83, 89, 196

java.lang.StringBuilder 218

Kingdom of Nouns 18

Download from Wow! eBook <www.wowebook.com>

324

INDEX

L

locking 14, 234, 236, 238, 250,

make-move 246

259–261

make-safe-array 260

lambda calculus 12

blocking 224, 248, 250–251,

make-smart-array 261

Lambda Papers 143

261, 265–266

manip-map 131–132

language, eager 113

contention 260–261

map 25, 68, 71, 78–79, 87, 

last 86

explicit locks 261

97–98, 100, 102, 119, 

laziness 113, 117, 119, 122,

fairness 250

129, 189, 204, 222, 269,

124, 274, 282

orphaning 238, 259

273–274, 295, 304

combinatorially exploding

reentrant 260

array map 98, 100, 190

computations 113

striping 261

PersistentHashMap 80

full realization 283

total ordering 238

thinking in maps 97

full realization of interim

log-agent 249

mapped file 74

results 117, 122

logarithmic 81

math-context 273–274

lazy evaluation 149

logging 249, 251

Maven 181

lazy sequences 68, 87, 131,

long 83, 279

max-history 247

268–269, 274, 283–284

look-around clauses 73

McCarthy, John 9

lazy-seq 115–116, 143

lookup 17–18, 68, 285–286

memoization 132, 256–257,

lazy-seq recipe 115, 117, 

loops 30–31, 146, 290

277, 284–287, 291

143

loop invariants 134

BasicCache 286

short-circuiting laziness 114

loop locals 31

cache 284–285

Leiningen 181

loop termination 46

caching protocol 286

let 29, 36, 52, 82, 117, 135, 137,

lowercase 74

hit 285–286

170, 273, 290

manipulable-memoize 

letfn 18, 147

M

256–257, 286

lexical scope 135, 273–274, 

memoization protocol 

290

M literal 21, 62–63

285–286

lexical bindings 309–310

macroexpand 161

memoize 256–257, 284–285

lexical context 138, 169

macroexpand-1 161

miss 285–286

lexical contour 170

macros 9, 24, 34, 55, 72,

PluggableMemoization 

lexical environment 138,

119, 160–161, 164, 166, 

286–287

140, 309

169–170, 173, 231, 263,

through 286–287

line number 55

296–298, 303, 305, 308,

Mersenne primes 283–284

line terminators 74

310–311

metadata 69, 71, 128, 164, 181,

linear search 100

combining forms 164

191, 256

Lisp (programming language

compile-time 31, 157, 161,

attaching 71

family) 4, 89, 22, 25, 30,

169, 230

meta 71, 191

36, 68, 79–80, 87, 90, 126,

hygienic 171

with-meta 71, 191

172, 202, 295, 298, 304

macro that builds another

methods 52, 55

beauty of 9

macro 297

metric units 294

cons-cell 79

macro-definition time 171

min-by 151, 154

Lisp-1 62, 72

macro-expansion time 169,

min-history 247

lists 24–25, 33, 79, 90–91, 122,

310

mini-language 8, 47, 298

159

returning functions 173

mixins 193

as stacks 91

rules of thumb 161

ML (programming

empty 44

selective Name

language) 12

PersistentList 90

Capturings 171

monitors 236, 259

singly linked 90

using to change forms 165

monitor context 259

literal 73

using to control symbolic 

monkey-patching 16, 195

literal syntax 23–25, 83, 89, 97,

resolution time 169

Montoya, Inigo 77

189

using to manage

more 48

live-lock 239

resources 171

Move 202, 205

local-context 138, 310

magical formula 269

multi-line mode 74

locals 29–30, 72, 117, 136, 143,

main 203

multimethods 15, 68, 70, 185,

272–273, 290

make-array 219

187–188, 202, 304–305, 307

local bindings 310

make-dumb-array 258

multimethod dispatch 221

Download from Wow! eBook <www.wowebook.com>

INDEX

325

multimethods (continued)

non-termination 113

pcalls 235, 268–269

prefer-method 187

non-thread-safe 75

peek 86, 91, 93, 192

remove-method 187

nouns 13

performance 190, 202, 277,

multiple transactions 246

ns-unmap 179

291

multiversion concurrency

nth 84, 91

measurements 282

control (MVCC) 236, 239

nthnext 116

Perl (programming

snapshot isolation 245

null 203

language) 135

write skew 239, 246

numbers 21–22

persistent data structures 7, 77,

mutability 78, 108–109, 136,

binary 22

81, 90, 110, 113, 280–281

220, 224, 235, 239, 255,

distribution of represented

persistent hash trie 81

259, 261, 280–282

numbers 65

pixel 51

isolated pools of mutation

hexadecimal 21–22

pmap 235, 268–269

points 298

octal 22

polling 255

mutable fields 202

promotion 63–64

polymorphism 3, 16, 139–141,

mutable state 14

radix notation 22

184–185, 188–189, 192–

mutation 109, 235, 239, 257,

radix-32 22

194, 202, 206

298

scientific notation 22

pool 251

mutators 202

numerical precision 75

pop 86, 91–93, 192

pos 101–103

N

positionally 47

O

postconditions 133, 173, 175,

name resolution 72

302

object-oriented

name shadowing 72, 169

pow 142–143

programming 3, 5, 8,

named arguments 133

precision 62–63

13, 15, 18–19, 32, 97, 164,

named structures 50

arbitrary precision 21

205–206, 292, 303, 305

namespaces 17, 21, 36, 39,

preconditions 173, 206, 302

conflict resolution

42, 69, 71, 94, 163, 169,

predicates 103, 138

strategy 187

178, 180–182, 189, 198,

type-based 79, 102

hierarchies 5, 18, 103, 164,

212–213, 215, 262, 270,

prefix notation 9, 25

204, 298, 304

272, 305

primitives 21, 64, 83, 200, 229,

objects 279

as class specifications 212

279, 287, 290–291

obscure 47

compilation 214

println 30, 114, 160, 308–309

occur-count 288–289

in-ns 179

print-method 92

On Lisp 298

name-mangled local 290

programmer efficiency 278

one-at-a-time realization

namespace compilation 214

Programming Clojure 101

282–284

namespace qualification 69

promises 235, 261, 266–267,

operator precedence 5, 25

ns 39, 70, 179, 182, 212

269

privacy 181

optimizations 277, 280, 289

callback API to blocking

qualification 40, 69, 170,

option flags 74

API 266

179, 183

or (logical) 49, 305

deliver 265

remove-ns 180

original map 49

promise 149, 265–266

two-level mapping 178, 180

with-promises 268

user 21

P

protocols 15–16, 121, 189, 192,

natural language 296

195, 197, 227, 258, 285,

neighbors 85–86, 150, 242

pair 49

305

nest 236

parallelism 149, 235, 261,

design of 285

nested syntax-quotes 297

264–266, 269

Prototype Principle 183

new 36

dataflow 267

prototyping 214

next 46, 57, 79, 89–91, 110,

parentheses 9

proxies 305

115–116

parents 186

construct-proxy 212

nil 24–25, 44–45, 49, 56, 78,

partial 127–128, 130, 242

proxy 38, 171, 208, 210–212,

80, 94, 101, 110, 117,

partition 298

261, 304

163, 195, 253

Patriot missile 64–65

proxy-mappings 210

nil pun 57

pattern matching 47, 249

proxy-super 211

nondeterminism 235

patterns 54, 73

update-proxy 210, 212

Download from Wow! eBook <www.wowebook.com>

326

INDEX

pure virtual classes 192

tail-call optimization

reuse 127

purely functional 131, 282

(TCO) 6, 145–146

reverse 41, 87

push 192–193

tail-recursive 124, 142, 154

roll 288–289

pvalues 235, 268–269

tail-recursive self-call 144

root binding 28, 270–271

Python (programming

reduce 119, 129, 180, 280, 304

root cause 55

language) 6, 44, 126, 132

refactoring 290

rounding error 64

reference types 14, 108, 110,

rseq 80, 84

Q

165, 202, 235–236, 240,

RSS2 262, 299

242, 245, 247, 252, 255,

rss-children 266, 299

Qi (programming language) 12

257–259, 261, 270, 272,

rsubseq 99

queues 91, 93, 252–253

303–304

Ruby (programming

PersistentQueue 91–92

add-watch 164, 303

language) 16, 135, 163

priority queues 192

coordinated 240–244, 247

unless 163

queue-fish 92

remove-watch 303

runtime 141

quicksort 121–123

set-validator 241

qsort 122–123

synchronous 241, 247, 252,

S

quote 32–34, 70, 159, 171

255

quoting forms 161

uncoordinated 255

SafeArray protocol 258–259

nested syntax-quotes 160

uniform state change

Scala (programming

syntax-quote 34, 163

model 242

language) 47, 126, 145,

watchers 304

170, 207, 301

R

referential transparency 12, 132

scalar 61

reflection 279–280, 289

scalar types 75

range 51, 68, 83, 90, 117, 282

Refs 235, 240–241, 243–246,

duality of 48, 62

rationals 22, 66

255

Scheme (programming

denominator 22, 67

alter 242, 244–245

language) 87, 143–145

numerator 22, 67

commutative 245

actors 143

ratio 66

commute 244–245

screaming-filter 211

rational? 65–67

ensure 239, 246

self 185

rationalize 66–67

ref-set 245

semantic coupling 302

read 309–310

regular expressions 52, 61, 75

separation of concerns 7

reader feature 28

case insensitivity 74

seq 46, 74, 77–80, 83–84, 98,

Read-Eval-Print Loop

re-find 75

200

(REPL) 21, 26, 32, 39, 

regex 73–74

seq protocol 305

54–55, 57, 97, 117, 123,

re-groups 75

seq1 283–284

179, 213–214, 221, 267,

reluctant quantifiers 73

sequence abstraction 77–78,

270, 273, 278, 289, 309

re-matcher 75

80, 82, 97, 100–101, 204

read-time 73

re-seq 74–75

rest vs. next 116

recompiled 73

reify 38, 141, 198, 208, 211, 304

sequences 78–80, 290

records 189, 191, 195, 197–198,

factory function 198

chunked 277, 282–283, 291

205–206

relational functions 293–294

chunk-at-a-time model 282

recur 30–31, 142, 144–147, 200

SELECT 10, 293

sequentials 48, 78–79

recursion 30, 141–142

relative-units 296, 298

server 209

accumulator 143

rem 55

set 37

explicit tail-call

remainder 55

sets 25, 79, 94

optimization 145

remote-procedure call

difference 97

freeing the recursive call 142

(RPC) 262, 266–267

intersection 96

generalized tail-call

rename 42

relative complement 97

optimization 145

reordering 245

union 97

mundane 142–143, 145, 306

replace 85

setter 204

mutual 142, 145–147

reset 255

shared structure 112

recursive call trapped 142

resolve 72, 272

shared-state concurrency 234

stack consumption 142

rest 46, 78, 80, 89, 91, 115–116,

short 83

tail 30, 145

121, 127

shorts 279

tail position 30–31, 143, 146

reusability 234

shuffle 226

Download from Wow! eBook <www.wowebook.com>

INDEX

327

side effects 29, 131–132, 154,

subseq 95, 99

transactions 235–236, 239, 241,

163, 180, 248, 255, 306

subvec 88–89

243–248, 255–257

simplicity 4, 103, 288

superclass constructor 212

embedded transactions 236

simplification 204

Sussman, Gerald 143

retry 236, 243, 247–248, 255,

single quote 33

Swank-Clojure 309

258

sleep 246, 252

swap 255, 257

size of 247

slice 228

Swing 126, 216

transients 108, 277, 280–282,

Sliceable 229

Sybil 62

291

sliceCount 228

symbols 23, 26, 28, 70–71, 159,

Rule of Transients 280

slope 133–134

171, 178, 264

TreeNode 189, 193, 195, 201

slowly 257, 287

auto-qualification 34

trees 110–111, 166, 168, 195,

snapshot 235–236

symbolic mappings 179

262, 283, 306

isolation 236

syntax 5, 7, 9

binary 113

software transactional memory

syntactic sugar 222

persistent binary 191

(STM) 3, 235–238, 243,

syntax-quote 32, 34–35, 72,

245–246, 248, 255

160–161, 169, 171

red-black 113

barging 239

nested 160

traversing 111, 306–307

commit 236, 243, 245–246

unbalanced 113

commit-time 245

T

triangle 118

in-transaction 243, 245–246

truncation 62, 290–291

retry 236

tail position 142

truthiness 43–44, 56

some 94

and recur targets 145

truthy 52, 69, 94, 119

sometimes-slowly 257

tail recursion 143

tuning 247

sort 47, 225

tail recursive 151

tweet-items 266

sort-by 129–130

tail-call 144

tweetless-rss-children 300

sorted-map 98–99, 113

take 124

tweet-occurrences 264

sorted-map-by 95, 99

terminating condition 46

Twitter 262–264, 299

sorted-set 94–95, 113

test-driven development (TDD)

type conversion, automatic 63

sorted-set-by 95

109, 292, 298–301

type hints 228, 277–280, 

sort-parts 123

specification language 302

287, 291

special form 24, 26, 33

unit tests 128

types 189, 227, 304–305

split 74–75

there ain’t no such thing as a

deftype 38, 200–202

spot optimizations 280

free lunch 237

spreadsheets 130, 139, 268

third-party libraries 171, 194,

U

SQL 10–11, 293–294

198

this 108, 171, 185, 198, 210–211

sqr 302

thread-bound 272

unbox 289

stack overflow 115

thread-local 28, 240, 270, 273

unchecked 64

errors 145

thread-local bindings 271–273,

unchecked-inc 289

stack trace 55

306

underscores 181

stacks 86, 91

threads 5, 28, 220, 224, 236,

Unicode 73

IPersistentStack 201

240–241, 247, 249–252,

case insensitivity 74

state 3, 13–14, 186, 202,

254–255, 258, 260–261,

234–235, 239, 242, 

unit conversions 294–295

265, 267–268, 274, 282,

245, 247, 249, 255

unit testing 128, 292, 298, 302

308

managing 238

unit-of-distance 297

starved 250

static type system 278

Universal Design Pattern

thread-safe 211, 240

static versus dynamic 278

(UDP) 183–186, 188

time 13, 235, 247

Steele, Guy Lewis 47, 143

timelines 235, 243

Unix line terminator 74

straight-line path 150

to-array 220

unmodifiable 226

stress 246

to-array-2d 220

unquote 35, 160, 163–164

strings 23, 71, 73, 79

toString 204–205

unquote-splice 35, 163

zero-length strings 44

trampoline 147

up-arrow key 51

structural sharing 110

trampoline for mutual

update-in 85

stubbing 299

recursion 147

uppercase 74

Download from Wow! eBook <www.wowebook.com>

328

INDEX

V

verbs 13

wrapping 195

very bad things 259

write-once 265

validation 205

visible 52

validator 241

void 212

X

variable arguments 26

volatile 202

variables 14, 29, 255

xconj 110, 112, 191, 193, 

Vars 25, 27, 32–34, 40, 72, 128,

W

195–196

137, 163–164, 178, 181,

xor 51

235, 240, 270, 307

when 8, 31, 52, 162–163, 170

xs 48

anonymous 272

when-let 120, 171

xseq 191, 200

root binding 164

when-not 163

var 270, 272

where-am-i 72

Y

var-get 272

while 8

with-local-vars 272–273

Yegge, Steve 183

vectors 24, 33, 80, 82, 98, 193

Whitehead, Alfred North 61

as stacks 86

whitespace, ignoring 74

IPersistentVector 193, 198

wit 73

Z

of names 49

with-binding 273

of primitives 83

with-open 82, 172, 274

Zawinski, Jamie (JWZ) 73

subvectors 88

with-out-str 273

zencat 281

vec 83

with-precision 273

zencat2 281

vector 29, 32, 83–84, 126,

with-redefs 300

zero 44

245, 295

with-resource 172

zipmap 98

vector-of 83

workflow 91

zipper 263

walking in reverse order 84

world 150–152

verbosity 140, 202

worst-case 81

Download from Wow! eBook <www.wowebook.com>

FUNCTIONAL PROGRAMMING

THE Joy OF Clojure

SEE INSERT

Fogus Houser

If you’ve seen how dozens of lines of Java or Ruby can dissolve

into just a few lines of Clojure, you’ll know why the authors

of this book call it a “joyful language.” Clojure is a dialect

“You’ll learn fast!”

of Lisp that runs on the JVM. It combines the nice features of a

—From the foreword

scripting language with the powerful features of a production

by Steve Yegge, Google

environment—features like persistent data structures and clean

multithreading that you’ll need for industrial-strength

“Simply unputdownable!”

application development.

—Baishampayan Ghose (BG)

Qotd, Inc .

The Joy of Clojure goes beyond just syntax to show you how to

write fl uent and idiomatic Clojure code. You’ll learn a functional

“Discover the why, not just

approach to programming and will master Lisp techniques

the how of Clojure.”

that make Clojure so elegant and effi

cient. Th

e book gives

—Federico Tomassetti

you easy access to hard soft ware areas like concurrency,

Politecnico di Torino

interoperability, and performance. And it shows you how

great it can be to think about problems the Clojure way.

“What Irma Rombauer

did for cooking, Fogus

What’s Inside

and Houser have done

Th

e what and why of Clojure

for Clojure.”

How to work with macros

—Phil Hagelberg, Sonian

How to do elegant application design

Functional programming idioms

Written for programmers coming to Clojure from another

programming background—no prior experience with

Clojure or Lisp is required.

Michael Fogus is a member of Clojure/core with experience in

distributed simulation, machine vision, and expert systems.

Chris Houser is a key contributor to Clojure who has

implemented several of its features.

For online access to the authors and a free ebook for owners

of this book, go to manning.com/TheJoyofClojure

M A N N I N G

$44.99 / Can $51.99 [INCLUDING eBOOK]