Clojure Elements: Data Structures and Functions

Clojure · v1.0.1

2026-11-14 14:53:58

Where we are

Where this fits

  • The previous unit placed Clojure: a functional Lisp, hosted on the JVM
  • This unit is the language itself: data structures, functions, program flow
  • The features are reference material: the book and the Clojure documentation cover each in detail
  • Most of this deck applies them to one problem: a university registrar

Outline of key topics

  • The unit at a glance: REPL, scalars, keywords, collections, sequences, functions, flow
  • A case study: modelling a registrar’s records as plain data
  • Small functions: projections, predicates, predicate factories
  • Nine queries built by composition: transcripts, GPAs, prerequisites, the dean’s list

The unit at a glance

The REPL

user=> (+ 1 2)
3
user=> (* *1 10)
30
user=> (doc first)
  • Read, evaluate, print, loop: every form is tried as it is written
  • *1, *2, *3: the last three results
  • doc, find-doc, apropos: documentation at the prompt

Scalars

(class 42)                    ;; java.lang.Long
(+ 1 2.0)                     ;; 3.0
(/ 1 3)                       ;; 1/3
(* 99999999999 99999999999N)  ;; 9999999999800000000001N
(if nil :t :f)                ;; :f
(if 0 :t :f)                  ;; :t
  • Numbers are JVM numbers; a ratio is exact; a double is contagious
  • Only nil and false are logically false; 0 and "" are true

Symbols and keywords

'ada                     ;; a symbol, as data
:ada                     ;; a keyword: evaluates to itself
(:name {:name "Ada"})    ;; "Ada"
  • A symbol names something and resolves to it when evaluated
  • A keyword is a value: the natural key for a map
  • A keyword is a function of a map: (:name m) looks itself up in m

Persistent collections

Collection Literal Good at conj adds
list '(1 2 3) the front (conj '(1 2) 0) ⇒ (0 1 2)
vector [1 2 3] indexing, the end (conj [1 2] 3) ⇒ [1 2 3]
map {:a 1 :b 2} lookup by key (assoc {:a 1} :b 2) ⇒ {:a 1, :b 2}
  • Every operation returns a new collection; the original is unchanged
  • Structural sharing keeps that cheap

The sequence abstraction

(first [1 2 3])       ;; 1
(rest {:a 1 :b 2})    ;; ([:b 2])
(cons 0 [1 2])        ;; (0 1 2)
  • first, rest and cons work on every collection
  • A map is a sequence of its entries, each a [key value] pair
  • Every sequence function works on every collection through this interface

Functions and local bindings

(defn hypot [a b]
  (let [a2 (* a a)
        b2 (* b b)]
    (Math/sqrt (+ a2 b2))))

(hypot 3 4)      ;; 5.0
(#(* % %) 5)     ;; 25
  • defn names a function
  • let binds local names, once each
  • #(...) is an anonymous function; % is its argument
  • do sequences side effects

Conditionals and iteration

(cond (pos? x) :positive
      (neg? x) :negative
      :else    :zero)

(loop [i 0 acc 0]
  (if (> i 5)
    acc
    (recur (inc i) (+ acc i))))   ;; 15
  • if, when, if-not, when-not, cond: choose a value
  • loop / recur: repetition without growing the stack

Higher-order functions and threading

(->> (range 10)
     (filter even?)
     (map #(* % %))
     (reduce +))                          ;; 120

(for [x [1 2 3] :when (odd? x)] (* 10 x))  ;; (10 30)

(-> {:name "Ada"} (assoc :year 3) (update :year inc))
;; {:name "Ada", :year 4}
  • ->> threads a value through the last argument; -> through the first
  • A pipeline reads in the order it runs

Case study: the Registrar

The problem

A registrar keeps three kinds of record:

  • courses: code, title, credits, prerequisites
  • students: id, name, program, year
  • enrollments: a student took a course, in a term, with a percentage grade

Questions to answer: transcripts, GPAs, students at risk, course averages, prerequisites, eligibility, the dean’s list.

Modelling: data, not classes

What Representation Why
an entity a map with keyword keys self-describing; keywords look themselves up
an identifier a keyword :csci1060, or an integer evaluates to itself; cheap equality
a lookup table a map from id to entity constant-time lookup
a relation a vector of maps one row per fact; every sequence function applies
membership a set the question asked of it is “is this a member?”

No class is defined: the library’s functions already work on every one of these.

The data: courses

(def courses
  {:csci1060 {:title   "Programming I"
              :credits 3
              :prereqs #{}}
   :csci2010 {:title   "Data Structures"
              :credits 3
              :prereqs #{:csci1061}}
   :csci3055 {:title   "Programming Languages"
              :credits 3
              :prereqs #{:csci2010 :csci2050}}
   ...})

The data: students and enrollments

(def students
  [{:id 1 :name "Ada"    :program :cs :year 3}
   {:id 4 :name "Edsger" :program :cs :year 1}
   ...])

(def enrollments
  [{:student 4 :course :csci1060 :term "2025-01" :grade 45}
   {:student 4 :course :csci1060 :term "2025-09" :grade 62}
   ...])
  • Six courses, five students, twenty-three enrollments
  • Edsger’s failed attempt and his retake are both kept: a history of facts

A modelling decision: terms that sort

First version

(sort ["2025F" "2025W"])
;; ("2025F" "2025W")

Fall sorts before Winter of the same year

Year and starting month

(sort ["2025-09" "2025-01"])
;; ("2025-01" "2025-09")

Alphabetical order is time order

Choose a representation that makes the standard functions correct.

Small pieces: grades

(defn letter [pct]
  (cond (>= pct 80) :A
        (>= pct 70) :B
        (>= pct 60) :C
        (>= pct 50) :D
        :else       :F))

(def points {:A 4.0 :B 3.0 :C 2.0 :D 1.0 :F 0.0})

(def grade-letter (comp letter :grade))
  • points is a map used as a function: (points :A) is 4.0
  • grade-letter composes two functions: :grade first, then letter

Small pieces: projections and predicates

(defn credits [e]
  (get-in courses [(:course e) :credits]))
(defn passed? [e] (not= :F (grade-letter e)))

(defn of-student [id] #(= id (:student %)))
(defn in-course  [c]  #(= c (:course %)))
  • Projection: an enrollment to a value — :grade, credits, grade-letter
  • Predicate: an enrollment to true or false — passed?
  • Predicate factory: a value to a predicate — (of-student 4) is a function

Grade-point average

(defn gpa [es]
  (let [cr (reduce + (map credits es))
        qp (reduce + (map #(* (credits %)
                              (points (grade-letter %)))
                          es))]
    (/ qp cr)))
  • Credit-weighted: quality points over credits
  • Takes any collection of enrollments: one student, one term, or one student in one term

Queries by composition

Q1: a transcript

(defn transcript [id]
  (->> enrollments
       (filter (of-student id))
       (sort-by :term)
       (map (juxt :term :course :grade grade-letter))))

(transcript 4)
;; (["2025-01" :csci1060 45 :F]
;;  ["2025-01" :math1010 58 :D]
;;  ["2025-09" :csci1060 62 :C]
;;  ["2025-09" :csci2050 51 :D])
  • juxt applies four projections to each enrollment, producing one row

Q2: every student’s GPA

(defn gpas []
  (->> enrollments
       (group-by :student)
       (map (fn [[id es]]
              [(name-of id) (round2 (gpa es))]))
       (into (sorted-map))))

(gpas)
;; {"Ada" 4.0, "Alan" 3.0, "Barbara" 3.54,
;;  "Edsger" 1.0, "Grace" 3.31}
  • group-by partitions the relation by a key function
  • [[id es]] destructures each group in the parameter list

Q3 and Q4: at risk, and course averages

(defn at-risk []
  (->> (gpas)
       (filter (fn [[_ g]] (< g 2.0)))
       (map first)))
;; ("Edsger")

(defn course-averages []
  (->> enrollments
       (group-by :course)
       (map (fn [[c es]]
              [c (round2 (average (map :grade es)))]))
       (into (sorted-map))))

(key (apply min-key val (course-averages)))
;; :csci1060
  • at-risk is a query over another query’s result
  • Course averages: the shape of Q2, with another key and another reduction

Q5: a grade distribution

(defn distribution [c]
  (->> enrollments
       (filter (in-course c))
       (map grade-letter)
       frequencies))

(distribution :csci1060)
;; {:A 2, :B 1, :C 2, :F 1}
  • frequencies counts each distinct value

Q6: prerequisites

(defn completed [id]
  (->> enrollments
       (filter (every-pred (of-student id) passed?))
       (map :course)
       set))

(defn can-take? [id c]
  (set/subset? (get-in courses [c :prereqs])
               (completed id)))

(can-take? 2 :csci3055)   ;; true
(can-take? 3 :csci3055)   ;; false
  • every-pred joins predicates: true when all of them hold
  • Prerequisites and completed courses are both sets: eligibility is one subset test

Q7: who is eligible for a course

(defn eligible [c]
  (->> students
       (map :id)
       (filter #(can-take? % c))
       (remove #(contains? (completed %) c))
       (map name-of)))

(eligible :csci3055)   ;; ("Alan")
(eligible :csci2010)   ;; ("Grace" "Barbara")
  • Eligible: every prerequisite passed, and the course not already passed

Q8: the dean’s list, per term

(defn deans-list []
  (->> enrollments
       (group-by (juxt :term :student))
       (filter (fn [[_ es]] (and (>= (count es) 2)
                                 (>= (gpa es) 3.5))))
       (map (fn [[[term id] _]] [term (name-of id)]))
       sort))
;; (["2024-09" "Ada"] ["2024-09" "Grace"]
;;  ["2025-01" "Ada"] ["2025-01" "Barbara"]
;;  ["2025-09" "Ada"])
  • (juxt :term :student) is a composite key
  • The same gpa computes a term GPA, unchanged

Q9: a query from predicates

(defn top-of-class [c]
  (->> enrollments
       (filter (every-pred (in-course c)
                           #(= :A (grade-letter %))))
       (map (comp name-of :student))))

(top-of-class :csci1060)   ;; ("Ada" "Barbara")
  • A new query, and no new function beyond the anonymous one
  • comp turns two lookups into one projection

Function first

Piece Used by
grade-letter Q1, Q5, Q9, passed?, gpa
gpa Q2, Q3, Q8
of-student, in-course Q1, Q5, Q6, Q9
completed Q6, Q7
name-of Q2, Q7, Q8, Q9
  • No query mutates the data, so queries run in any order — or at the same time

Each query is a pipeline of small functions; most of the pieces are shared.

Functions beyond the notes

Function Does Used in
group-by partitions a collection by a key function Q2, Q4, Q8
frequencies counts each distinct value Q5
juxt applies several functions, collects a vector Q1, Q8
comp composes functions, right to left grade-letter, Q9
every-pred joins predicates with “and” Q6, Q9
sort-by, min-key order or select by a key function Q1, Q4
set/subset? set containment Q6

Summary

Summary

  • Scalars, keywords, lists, vectors and maps are values
  • One sequence interface serves every collection
  • defn, let, loop/recur, and the threading macros
  • A domain modelled as maps, vectors and sets needs no classes
  • Queries are pipelines of small, named, shared functions
  • Immutable data: every query is safe to run in any order

Where next

Building Blocks of Clojure — the next unit in this module.

  • The registrar case study continues in later units: registration with seat limits is the concurrency example