Clojure Core Functions: A Quick Reference Guide

Explore essential Clojure core functions with concise explanations and practical examples for efficient programming.

Clojure Core Functions: This lesson explains how clojure Core Functions fits into Clojure design, where it helps, and which trade-offs matter in practice.

Unlock the power of Clojure with this quick reference guide to its core functions. Whether you’re manipulating collections, processing strings, or managing concurrency, this guide provides concise explanations and practical examples to enhance your Clojure programming skills.

Introduction

Clojure, a modern Lisp dialect, offers a rich set of core functions that facilitate functional programming. These functions are designed to work seamlessly with Clojure’s immutable data structures, enabling developers to write concise, expressive, and efficient code. In this guide, we will explore essential Clojure core functions across various categories, providing you with a handy reference for your development needs.

Collection Manipulation

Clojure’s collection manipulation functions are central to its functional programming paradigm. They allow you to transform, filter, and aggregate data with ease.

map

Description: Applies a function to each element of a collection, returning a new lazy sequence.

1;; Example: Increment each number in a list by 1
2(map inc [1 2 3 4])
3;; => (2 3 4 5)

filter

Description: Returns a lazy sequence of elements that satisfy a predicate function.

1;; Example: Filter even numbers from a list
2(filter even? [1 2 3 4 5 6])
3;; => (2 4 6)

reduce

Description: Reduces a collection to a single value using a binary function.

1;; Example: Sum all numbers in a list
2(reduce + [1 2 3 4 5])
3;; => 15

conj

Description: Adds an element to a collection, returning a new collection.

1;; Example: Add an element to a vector
2(conj [1 2 3] 4)
3;; => [1 2 3 4]

assoc

Description: Associates a key with a value in a map, returning a new map.

1;; Example: Add a key-value pair to a map
2(assoc {:a 1 :b 2} :c 3)
3;; => {:a 1, :b 2, :c 3}

dissoc

Description: Removes a key from a map, returning a new map.

1;; Example: Remove a key from a map
2(dissoc {:a 1 :b 2 :c 3} :b)
3;; => {:a 1, :c 3}

get

Description: Retrieves the value associated with a key in a map.

1;; Example: Get the value for a key in a map
2(get {:a 1 :b 2 :c 3} :b)
3;; => 2

merge

Description: Merges multiple maps into a single map.

1;; Example: Merge two maps
2(merge {:a 1 :b 2} {:b 3 :c 4})
3;; => {:a 1, :b 3, :c 4}

String Processing

Clojure provides a set of functions for efficient string manipulation, allowing you to handle text data seamlessly.

str

Description: Concatenates its arguments into a string.

1;; Example: Concatenate strings
2(str "Hello, " "world!")
3;; => "Hello, world!"

subs

Description: Returns a substring of a given string.

1;; Example: Extract a substring
2(subs "Clojure" 0 3)
3;; => "Clo"

clojure.string/split

Description: Splits a string into a sequence of substrings based on a regular expression.

1(require '[clojure.string :as str])
2
3;; Example: Split a string by spaces
4(str/split "Clojure is fun" #"\s")
5;; => ["Clojure" "is" "fun"]

clojure.string/join

Description: Joins a sequence of strings into a single string with a separator.

1;; Example: Join strings with a separator
2(str/join ", " ["Clojure" "is" "fun"])
3;; => "Clojure, is, fun"

clojure.string/replace

Description: Replaces all instances of a substring with another string.

1;; Example: Replace a substring
2(str/replace "Clojure is fun" "fun" "awesome")
3;; => "Clojure is awesome"

Concurrency and State Management

Clojure’s concurrency model is built around immutable data structures and provides powerful primitives for managing state.

atom

Description: Creates a mutable reference to an immutable value, allowing for safe state changes.

1;; Example: Create and update an atom
2(def counter (atom 0))
3(swap! counter inc)
4;; => 1

ref

Description: Provides coordinated, synchronous access to shared state using Software Transactional Memory (STM).

1;; Example: Create and update a ref
2(def balance (ref 100))
3(dosync (alter balance + 50))
4;; => 150

agent

Description: Manages asynchronous state changes, allowing for independent updates.

1;; Example: Create and update an agent
2(def counter (agent 0))
3(send counter inc)
4;; => 1

future

Description: Executes a task asynchronously, returning a future object representing the result.

1;; Example: Create a future
2(def result (future (+ 1 2 3)))
3@result
4;; => 6

promise

Description: Represents a value that will be delivered in the future, allowing for synchronization.

1;; Example: Create and deliver a promise
2(def p (promise))
3(deliver p 42)
4@p
5;; => 42

Data Structures

Clojure’s core data structures are immutable and persistent, providing efficient operations for functional programming.

vector

Description: An indexed, immutable collection that supports efficient random access.

1;; Example: Create a vector
2(def v [1 2 3 4])
3(nth v 2)
4;; => 3

list

Description: A sequential, immutable collection optimized for adding elements to the front.

1;; Example: Create a list
2(def lst '(1 2 3 4))
3(first lst)
4;; => 1

map

Description: An associative, immutable collection of key-value pairs.

1;; Example: Create a map
2(def m {:a 1 :b 2 :c 3})
3(get m :b)
4;; => 2

set

Description: An unordered, immutable collection of unique elements.

1;; Example: Create a set
2(def s #{1 2 3 4})
3(contains? s 3)
4;; => true

Functional Programming Techniques

Clojure’s core functions support functional programming techniques, enabling you to write expressive and concise code.

partial

Description: Creates a new function by partially applying arguments to an existing function.

1;; Example: Create a partially applied function
2(def add5 (partial + 5))
3(add5 10)
4;; => 15

comp

Description: Composes multiple functions into a single function.

1;; Example: Compose functions
2(def add1-and-double (comp #(* 2 %) inc))
3(add1-and-double 3)
4;; => 8

apply

Description: Applies a function to a sequence of arguments.

1;; Example: Apply a function to a list of arguments
2(apply + [1 2 3 4])
3;; => 10

fn

Description: Creates an anonymous function.

1;; Example: Create an anonymous function
2((fn [x] (* x x)) 5)
3;; => 25

Error Handling

Clojure provides mechanisms for handling errors and exceptions in a functional style.

try, catch, finally

Description: Provides a way to handle exceptions and ensure cleanup.

1;; Example: Handle exceptions
2(try
3  (/ 1 0)
4  (catch ArithmeticException e
5    (println "Cannot divide by zero"))
6  (finally
7    (println "Cleanup")))
8;; => "Cannot divide by zero"
9;; => "Cleanup"

Interoperability with Java

Clojure’s seamless interoperability with Java allows you to leverage existing Java libraries and frameworks.

import

Description: Imports Java classes for use in Clojure code.

1;; Example: Import a Java class
2(import 'java.util.Date)
3(Date.)
4;; => #inst "2024-11-25T00:00:00.000-00:00"

new

Description: Creates a new instance of a Java class.

1;; Example: Create a new Java object
2(new java.util.Date)
3;; => #inst "2024-11-25T00:00:00.000-00:00"

. (dot operator)

Description: Calls methods on Java objects.

1;; Example: Call a method on a Java object
2(.toString (new java.util.Date))
3;; => "Mon Nov 25 00:00:00 UTC 2024"

Practice Prompt

Experiment with the code examples provided in this guide. Try modifying the arguments, combining functions, or creating new functions to deepen your understanding of Clojure’s core functions.

Visualizing Clojure’s Core Function Workflow

Below is a diagram illustrating the workflow of using Clojure’s core functions for collection manipulation:

    graph TD;
	    A["Start"] --> B["Collection"]
	    B --> C["map"]
	    C --> D["filter"]
	    D --> E["reduce"]
	    E --> F["Result"]
	    F --> G["End"]

Diagram Description: This flowchart represents the typical process of transforming a collection using Clojure’s core functions: starting with a collection, applying map to transform elements, using filter to select elements, reducing the collection to a single value, and obtaining the final result.

Review Questions

To reinforce your understanding of Clojure’s core functions, try answering the following questions and challenges.

Loading quiz…
Revised on Thursday, April 23, 2026