Conao3 Notes

A Clojure core cheat sheet in math notation

I wrote down 163 functions from clojure.core that work on sequences, collections and functions, each as a small formula. I borrowed the notation from Daniel Keep's Rust Iterator Cheat Sheet (CC BY-SA 4.0) and moved it to Clojure syntax, with seqs, vectors, maps and sets written as Clojure literals and function calls written as lists. The rows describe Clojure 1.12.7. A script keeps every row next to 333 checks that run the function in Clojure, and it builds the tables only when all of the checks pass.

Reading the notation

The figure reads the take-while row, and then follows the same row through (take-while #(< % 3) (range)).

img

  • is a seq. and are input seqs, and a subscript picks one element.
  • is a list, is a vector, is a map, and is a set, as in Clojure source. The list rows of peek and pop need a real list, and a seq such as the result of map throws there.
  • calls with , as in Clojure source.
  • , and are functions that compute new values, and is a key function such as the one sort-by takes.
  • and are predicates. A predicate result counts as when it is anything other than or .
  • is a comparator, such as compare or >.
  • says that takes two arguments, and and name the kind of value it returns. is the accumulated value of a reducing function, and is its first value.
  • is a transducer, such as (map inc).
  • and are positions, except in range, where they are the start and end values. is a count that you pass in, is a step, and and are the lengths of the input seqs.
  • is a map, is a key, and are values, and is a default value.
  • is a function, the same as (fn [x] (f x)). takes any number of arguments.
  • A superscript ! marks a transient, as in .
  • is a permutation of the positions, and "wh." reads "where". Other letters name values that appear in the arguments or that the row defines after "wh.".
  • An underlined element stays unrealized after you call the function and consume every seq in its result. (take-while p a) has to look at to know where to stop, so I underline only the elements after . I measured this on an unchunked lazy seq. Over a vector or a finite range, many lazy functions such as map and filter compute 32 results at a time, because vectors and finite ranges give chunked seqs.
  • A check in the Lazy column means the function returns a lazy seq, which computes its elements when you ask for them.
  • A check in the xf column means the function returns a transducer when you call it without the collection, as in (map inc).
  • The function name links to its entry in the clojure.core API reference.

How I grouped the functions

The official Clojure cheat sheet groups its "Seq in, Seq out" functions under headings such as "Get shorter", "Get longer", "Head-items", "Tail-items" and "'Change'". Some functions sit under two of those headings, such as filter, which appears under "Get shorter" and "'Change'".

I grouped each function by how the elements of its result relate to the elements of its input, so each function appears once.

  • Selecting: every result element is an input element, in the input order.
  • Transforming: the result elements are values that computes from the input elements.
  • Combining: the result adds elements to a seq, or joins several seqs or nested collections into one seq.
  • Reordering: the result has the same elements in another order.
  • Splitting: the result holds the input elements in groups.
  • Reducing: the result is one value.
  • Collecting: the result is a vector, a set, a map, or the collection you pass to into.

Rich Hickey described the argument order of clojure.core in a mailing list thread in 2008:

Sequence functions take their sources last and collection functions take their primary operand (collection) first.

Most functions in the groups above are sequence functions, so the seq comes last and they work with ->>. nth, nthrest and nthnext take the seq first, and max-key and min-key take values instead of a seq. The functions that read or update a vector, map or set take it first and work with ->. After them come the functions that build collections, test what kind of collection a value is, work on transients, and compare values.

Making a seq

These functions make a seq from nothing, from a value or from a collection. Without a transducer, sequence only turns its argument into a seq, so a vector gives a chunked seq and a lazy seq comes back as it is.

FunctionArgumentsResultLazyxf
seq
sequence
, ✓
list*, ,
re-seq, ✓
,
subseq, ,
, , ✓
, , , , ✓
rsubseq, ,
, , ✓
, , , , ✓
range✓
,
, ,
repeat✓
,
repeatedly✓
,
iterate, ✓
keys
vals
rseq

Selecting by position

These functions keep or drop elements by counting. rest returns an empty seq when nothing is left, and next returns , so next has to realize one more element to find out.

FunctionArgumentsResultLazyxf
take, ✓✓
drop, ✓✓
take-last,
,
drop-last✓
,
butlast
rest
next
nnext
nfirst
nthrest,
,
nthnext,
,
take-nth, ✓✓

Selecting by predicate

These functions keep or drop elements by testing each one, or by comparing it with the elements before it.

FunctionArgumentsResultLazyxf
filter, ✓✓
remove, ✓✓
filterv,
take-while, ✓✓
drop-while, ✓✓
distinct✓✓
dedupe✓✓
random-sample, ✓✓

Transforming

These functions compute new elements from the input elements. With more than one input seq, map stops at the end of the shortest one.

FunctionArgumentsResultLazyxf
map, ✓✓
, ,
mapv,
pmap, ✓
map-indexed, ✓✓
keep, ✓✓
keep-indexed, ✓✓
mapcat, ✓✓
replace, ✓✓
,
reductions, ✓
, ,

Combining

interleave stops at the end of the shortest seq, and flatten replaces each nested sequential collection, such as a vector or a list, with its elements.

FunctionArgumentsResultLazyxf
cons,
concat, , ✓
interleave, ✓
interpose, ✓✓
cycle✓
flatten✓

Reordering

sort and sort-by are stable, so equal elements keep their input order.

FunctionArgumentsResultLazyxf
reverse
sort
,
sort-by,
, ,
shuffle

Splitting

partition and its relatives return a seq of groups, and split-at, split-with and splitv-at return a vector of two parts.

FunctionArgumentsResultLazyxf
partition, ✓
, ,
partition-all, ✓✓
partition-by, ✓✓
split-at,
split-with,
partitionv, ✓
partitionv-all, ✓✓
splitv-at,

Reducing to a value

These functions consume a seq and return one value. some, every?, not-every? and not-any? stop at the first element that decides the answer. transduce calls with one argument at the end, and completing adds that arity to a two-argument function.

FunctionArgumentsResultLazyxf
reduce,
,
,
, ,
, ,
reduce-kv, ,
transduce, , ,
count
first
second
fnext
when-first,
,
last
nth,
,
, ,
ffirst
rand-nth
some,
every?,
not-every?,
not-any?,
empty?
not-empty
distinct?, ,
max-key, , ,
min-key, , ,

Collecting into a collection

The result is a vector, a set or a map that holds the elements of the seq, or the collection you pass to into with the elements added.

FunctionArgumentsResultLazyxf
into,
,
,
, ,
vec
set
zipmap,
frequencies
group-by,

Collections

These functions take the collection first. conj adds at the end of a vector and at the front of a list. assoc, dissoc, conj, merge and empty keep the type of their first argument, such as a sorted map, and select-keys, update-keys and update-vals return a plain map.

FunctionArgumentsResultLazyxf
conj,
,
,
,
,
disj,
assoc, ,
, ,
dissoc,
get,
,
, ,
,
get-in,
assoc-in, ,
update, ,
, , , ,
update-in, ,
update-keys,
update-vals,
merge, ,
merge-with, ,
select-keys,
contains?,
,
find,
,
key
val
peek
pop
subvec, ,
,
empty

Constructing collections

These functions build a collection from the values you pass. array-map keeps the keys in the given order until you assoc more keys onto a map that has more than 8 entries, which turns it into a hash map. The sorted variants keep their keys ordered by compare or by the comparator you pass.

FunctionArgumentsResultLazyxf
list, ,
vector, ,
vector-of, ,
hash-map, , , ,
array-map, , , ,
sorted-map, , , ,
sorted-map-by, , , , ,
hash-set, ,
sorted-set, ,
sorted-set-by, , ,

Predicates on collections

Each predicate tells you what kind of collection a value is. A Clojure map entry is a vector of a key and a value, so vector?, sequential? and indexed? return true for it.

FunctionArgumentsResultLazyxf
coll?
seq?
seqable?
sequential?
associative?
counted?
reversible?
sorted?
indexed?
list?
vector?
map?
set?
map-entry?

Transients

A transient is a version of a vector, hash map or hash set that you make in constant time, change with the functions that end in !, and turn back into a persistent collection. Each of those functions returns the updated transient, and you keep using that return value. Sorted collections and lists have no transient version.

FunctionArgumentsResultLazyxf
transient
persistent!
conj!,
assoc!, ,
, ,
dissoc!,
disj!,
pop!

Comparing and testing values

= compares values, so a vector and a list with the same elements are equal, and identical? compares objects. (= 1 1.0) is false, because integers and floating-point numbers are never = to each other; (== 1 1.0) compares them as numbers. compare is the default order of sort and the sorted collections. It orders numbers by value across types, so (compare 1 1.0) is 0, and it orders vectors by length first and then element by element. Lists, sets and maps do not implement Comparable, and compare throws on them.

FunctionArgumentsResultLazyxf
=, ,
not=, ,
identical?,
compare,
nil?
some?
true?
false?
not
instance?,
record?

Functions

Each function here builds, calls or wraps functions.

FunctionArgumentsResultLazyxf
identity
constantly
comp, ,
partial, ,
apply, , ,
complement
juxt, ,
fnil,
every-pred, ,
some-fn, ,
trampoline, ,
memoize

These functions control when Clojure realizes a seq, run side effects, or help you write transducers, so I describe them in words.

Function What it does
doall Realizes a lazy seq and returns it.
dorun Realizes a lazy seq for its side effects and returns nil.
run! Calls a function on each element for its side effects and returns nil.
doseq A macro that runs a body for each element, with the bindings of for.
for A macro for list comprehension that returns a lazy seq.
realized? Tells whether a lazy seq, delay, future or promise already has its value.
lazy-seq A macro that makes a lazy seq from a body that returns a seq.
lazy-cat A macro version of concat that evaluates each collection expression only when needed.
iteration Makes a seqable and reducible value from repeated calls to a step function, such as fetching pages of an API.
tree-seq Walks a tree depth first and returns the nodes as a lazy seq.
eduction Applies transducers to a collection each time you reduce or iterate it.
cat A transducer that concatenates the collections it receives.
halt-when Returns a transducer that stops the reduction at the first input that satisfies a predicate.
completing Adds a completion arity to a reducing function, for use with transduce.
reduced Wraps a value so that reduce stops and returns it.
bounded-count Counts the elements of a seq, stopping after a given number.
reduced? Tells whether a value is wrapped by reduced.
unreduced Takes the value out of a reduced wrapper, and returns other values as they are.
ensure-reduced Wraps a value with reduced unless it is wrapped already.
seque Makes a queued seq that realizes another seq in the background, up to n items ahead of the consumer.
iterator-seq Makes a seq from a java.util.Iterator.
enumeration-seq Makes a seq from a java.util.Enumeration.
line-seq Makes a lazy seq of the lines read from a java.io.BufferedReader.
file-seq Walks a directory tree and returns its java.io.File objects as a lazy seq.
xml-seq Walks a tree parsed by clojure.xml/parse and returns its elements and text nodes as a lazy seq.
resultset-seq Makes a lazy seq of maps from the rows of a java.sql.ResultSet.
to-array Copies a collection into a Java Object[].
to-array-2d Copies a collection of collections into a Java Object[][].
into-array Copies a seq into a Java array of a given element type, or of the first element's type.
deref Reads the value of a reference such as an atom, a delay, a future or a promise; @x is short for it.
bean Makes a read-only map view of a Java object from its JavaBean properties.

I left out the rest of clojure.core, which includes numbers, strings, concurrency, namespaces, macros for control flow and the other parts of Java interop.