How to define a function in Clojure

Functions

Functions are generally code blocks that carry out certain execution in an application. This block of code can be called more than once during the execution of the application.

Define a function in Clojure

In Clojure, a function is defined using the defn keyword, followed by the function's name.

Syntax

(defn nameoffunction
“documentation string”
[arguments]
(code block))
Function definition syntax

Unlike most programming languages that use parenthesis () to pass arguments and curly braces {} for a code block, Clojure uses the square bracket [] to pass arguments and the parenthesis () for code block.

Example

Let's look at an example of how to define a function.

(defn func []
(println "Hello World"))
(func)

Explanation

  • Line 1: We define a function func. The documentation string specified in the syntax is optional, and because we are performing a simple print function, passing a variable was not needed.
  • Line 2: We print use, as specified by the syntax, where the code block should be.
  • Line 3: We call the (func) function.
Note: We did not call the (func) function as we do in other languages.

Free Resources