Clojure Functions with defn — The One Form You Need | Episode 4
0views
C
CelesteAI
Description
Functions are Clojure's main building block. In this episode we cover defn — the one form you use to define every named function in your codebase. By the end you'll know parameters, return values, docstrings, and multi-arity, and you will have written a functions.clj file that ties them all together.
No classes, no method vs. function distinction, no void return types. Just defn.
Student code: https://github.com/GoCelesteAI/clojure-for-beginners/tree/main/episode04
Every keystroke is shown on screen with generous pauses so you can follow along at your own pace.
What You'll Learn:
- defn — the canonical way to define a named function
- Parameters in a vector after the function name
- Return values — the last expression in the body is what comes back, no return keyword
- Docstrings — an optional string between name and parameter vector
- Multi-arity — one function with different bodies for different argument counts
- Writing and running functions.clj with :!clj -M %
Key REPL Demo:
(defn greet [name] (str "Hello, " name)) defines greet
(greet "Ada") returns "Hello, Ada"
(defn add [a b] (+ a b)) two arguments
(add 3 5) returns 8
(defn square [x] (* x x)) last expression returns
(square 7) returns 49
Timestamps:
0:00 - Intro
0:12 - Preview: the one form for functions
0:27 - Start the REPL
0:31 - A simple function: greet
0:45 - Multiple arguments: add
0:57 - Return value is the last expression: square
1:11 - Exit the REPL with Ctrl+D
1:16 - Write functions.clj in Neovim
1:38 - Simple function section
2:12 - Math section — add and square
3:05 - Docstring section — cube
3:40 - Multi-arity section — hello
4:40 - Run with :!clj -M %
4:44 - Output explained line by line
5:40 - Review the file
5:44 - Recap
6:10 - What's next — Episode 5
Key Takeaways:
1. defn defines a named function in one form. Parameters go in a vector after the name.
2. The last expression in the body is always the return value. No return keyword in Clojure.
3. One function can have multiple arities — wrap each arity in its own (params body) parens.
Series Roadmap:
- Episodes 1-6: REPL & first values
- Episodes 7-13: Collections & sequences
- Episodes 14-19: Functional core
- Episodes 20-24: Namespaces, projects, testing
- Episodes 25-30: State & concurrency
- Episodes 31-35: Data modeling
- Episodes 36-38: Macros
- Episodes 39-41: Interop, Babashka, uberjars
- Episodes 42-45: Capstone — web app deployment
Next up — Episode 5: Conditionals (if, when, cond).
Taught by CelesteAI. Like & subscribe for more Clojure tutorials!