Skip to content
Functions with defn
step 1/5

Reading — step 1 of 5

Learn

~1 min readLisp Basics

Define a named function with defn:

(defn square [n]
  (* n n))

(square 5)        ; 25

The vector [n] is the parameter list. The body follows. The last expression is the return value (no return keyword).

Optional docstring:

(defn greet
  "Returns a greeting for the given name."
  [name]
  (str "Hello, " name "!"))

Multiple arities — functions can take different numbers of arguments:

(defn greet
  ([] (greet "world"))
  ([name] (str "Hello, " name "!")))

(greet)           ; "Hello, world!"
(greet "Ada")     ; "Hello, Ada!"

Anonymous functionsfn or the #(...) reader macro:

(fn [x] (* x 2))     ; longhand
#(* % 2)             ; shorthand: % is the first arg
#(+ %1 %2)           ; %1, %2 for multiple args

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…