Idiomatic Function Names in Clojure

If you’re new to Clojure, ClojureScript, or any other Lisp, you might be confused by the exclamation and question mark suffixes in some function names (e.g., even?, odd?, empty?, swap!, enable-console-print!) and the occasional function or variable name wrapped in asterisks or earmuffs (e.g., *print-fn*, *out*).

But first things first, what does idiomatic even mean? Here’s the definition from the New Oxford American Dictionary:

idiomatic |ˌidēəˈmatik|
1 using, containing, or denoting expressions that are natural to a native speaker: distinctive idiomatic dialogue
2 appropriate to the style of art or music associated with a particular period, individual, or group: a short Bach piece containing lots of idiomatic motifs

Translation: Function names are idiomatic when they’re natural and grammatically correct to the community using them. As such, using suffixes and prefixes in function and variable names is a convention many Lispers share.

According to the Clojure Style Guide, it’s idiomatic to use the exclamation mark as a suffix for non-pure functions, that is, functions that have side effects.

(def x (atom 2))
(swap! x (fn [n] (* n n))) ;=> 4
(swap! x inc) ;=> 5
(swap! x dec) ;=> 4
(reset! x 0) ;=> 0

The question mark is used for boolean functions that evaluate to true or false.

(empty? []) ;=> true
(even? 23) ;=> false
(neg? 23) ;=> false
(pos? 23) ;=> true
(zero? 0) ;=> true

Last but not least, Clojure’s Library Coding Standards tell us that *earmuffs* should only be used for things intended for rebinding.

Note: The characters !?* have no special semantics in Clojure (as is the case with many other languages), they’re just part of the function or variable name.

Next: The ClojureScript REPL
Previous: Delegates in Objective-C