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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources