Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

Your First Clojure Program

Write and run a first Clojure program: project layout, ns declarations, require and refer, defn, println, the -main function, command-line arguments and running with the CLI.

You have a REPL and you know how forms are evaluated. Now it is time to put code in a file, give it a namespace and run it as a program. This lesson walks through a tiny project from an empty folder to a working command-line program, and explains namespaces, which organize all Clojure code.

Project layout

Create a folder named hello with this structure:

TEXT
hello/
  deps.edn
  src/
    hello/
      core.clj

The deps.edn file can be nearly empty for this program:

CLOJURE
{:paths ["src"]}

The file path must match the namespace name: a namespace hello.core lives in src/hello/core.clj. Hyphens in a namespace become underscores in file names, so my-app.core is stored in src/my_app/core.clj. Getting this wrong is the most common beginner error, and the message is "Could not locate ... on classpath".

The namespace declaration

Every file starts with an ns form:

CLOJURE
(ns hello.core
  (:require [clojure.string :as str]))

ns creates (or switches to) the namespace hello.core. :require loads another namespace and gives it a short alias, so you can write str/upper-case instead of clojure.string/upper-case. Common variations:

CLOJURE
(ns hello.core
  (:require [clojure.string :as str]                 ; alias
            [clojure.set :refer [union difference]]  ; bring in specific names
            [clojure.java.io :as io])
  (:import (java.time LocalDate)))                   ; a Java class

Avoid :refer :all in real code: it hides where a name comes from. Prefer an alias.

The program

Put this in src/hello/core.clj:

CLOJURE
(ns hello.core
  (:require [clojure.string :as str])
  (:gen-class))

(defn greeting
  "Builds a greeting for the given name."
  [name]
  (str "Hello, " (str/capitalize name) "!"))

(defn -main
  "Entry point. Prints a greeting for each argument."
  [& args]
  (if (seq args)
    (doseq [name args]
      (println (greeting name)))
    (println (greeting "world"))))

Here is what is new:

  • defn defines a named function: name, optional docstring, parameter vector, then the body. The value of the last expression is what the function returns.
  • -main is the conventional entry point. [& args] collects the command-line arguments into a sequence (or nil when there are none).
  • (seq args) returns nil for an empty collection, so it doubles as "has anything?". You will meet this idiom everywhere.
  • doseq loops for side effects (printing); println writes a line to standard output.
  • (:gen-class) is only needed when you compile an ahead-of-time (AOT) jar; running from source does not need it.

Running it

From the hello folder:

Terminal
clojure -M -m hello.core
clojure -M -m hello.core ada grace

-M means "run main", -m hello.core names the namespace whose -main to call. The second command prints one greeting per argument. If you prefer to see the result inside a REPL:

CLOJURE
user=> (require 'hello.core)
user=> (hello.core/greeting "ada")
"Hello, Ada!"
user=> (hello.core/-main "ada" "grace")
Hello, Ada!
Hello, Grace!

After editing the file, reload it with (require 'hello.core :reload) and call the function again. Editor-connected REPLs do the same by evaluating the whole file.

From file to running program

Folder layout src/hello/core.clj
ns form Names the namespace, requires others.
defn Define functions, including -main.
Run clojure -M -m hello.core
1 / 2

Printing and strings

Four print functions are worth knowing:

Function Behaviour
println Human-friendly output followed by a newline
print Like println without the newline
prn Machine-readable output (strings keep their quotes) followed by a newline
pr-str Returns the prn text as a string instead of printing
CLOJURE
(println "name:" "Ada" 36)  ; name: Ada 36
(prn "name:" "Ada" 36)      ; "name:" "Ada" 36
(str "a" 1 :b nil)          ; "a1:b"
(format "%05.1f|%-6s|" 3.14159 "ab")  ; "003.1|ab    |"

str joins the printed form of anything (and treats nil as an empty string). format uses Java's format directives. When debugging, prn is usually better than println because it shows quotes and keeps data readable.

A reusable function, tried in the browser

The greeting logic can be modelled in JavaScript. This stand-in mirrors the shape of the Clojure program: a pure function plus an entry point that handles the "no arguments" case.

JS Stand-in: greeting and -main

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that greeting returns a string and does no printing, while main performs the output. Keeping the pure part separate from the side effects is a habit you will want in Clojure: the pure function can be tested in the REPL without any output.

Common mistakes

  • File and namespace mismatch. ns hello.core must live in hello/core.clj.
  • Forgetting the parameter vector. (defn f (str "x")) is an error; write (defn f [] (str "x")).
  • Parentheses in the wrong place. Let the editor balance them and indent your code; the indentation shows the nesting.
  • Calling -main without & args. With [& args] the function accepts zero or more arguments; with [] it accepts none and fails when you pass any.

Another stand-in shows how str and nil interact, since this surprises newcomers:

JS Stand-in: str treats nil as empty

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must the namespace my-app.core be stored?

    Dots become directories and hyphens become underscores in the file path.
  2. 2. What does [& args] do in a parameter list?

    & marks the rest of the arguments, which arrive as a sequence (or nil when none are passed).
  3. 3. How do you run the main function of namespace hello.core with the Clojure CLI?

    -M selects main options and -m names the namespace whose -main function is called.
  4. 4. What does (str "a" nil "b") return?

    str treats nil as an empty string, so the result is "ab".

Summary

  • A project needs deps.edn and a source folder; the namespace name must match the file path.
  • ns declares the namespace; :require with :as loads others under a short alias.
  • defn defines functions; -main with [& args] is the command-line entry point.
  • Run with clojure -M -m your.namespace, or load it into a REPL with require.
  • println for people, prn for data; str ignores nil.

Next: Numbers and Arithmetic