What is apply() in Clojure?

Clojure is a modern parallel programming language that operates on the Java Virtual Machine (JVM), the common language runtime (CLR), and JavaScript engines.

The apply() function

The apply() function in Clojure allows you to call a function with various arguments. It takes a function and a list of arguments, and then it applies the function to the arguments in the list.

The apply() function comes in handy when you have a collection of arguments to provide to a function and don't want to manually extract and pass each parameter.

Syntax

The syntax of the apply function is given below:

(apply function arguments)
Syntax of apply() function
  • function is a required parameter and is the function that you want to apply.

  • arguments is a required parameter showing a list of arguments you want to pass to the function.

Code

Let's go through a basic code example that implements the apply() function in Clojure:

(def numbers [1 2 3 4 5])
(defn sum-of-numbers [nums]
(apply + nums))
(def total-sum (sum-of-numbers numbers))
(println "Total Sum:" total-sum)

Code explanation

  • Line 1: Firstly, we define a list of numbers [1 2 3 4 5] and store it in the variable numbers.

  • Line 3–4: Next, we define a function sum-of-numbers that takes the argument nums and uses the apply function to calculate the sum of the numbers in the nums list using the + operator.

  • Line 6: Now, we call the sum-of-numbers function with the numbers list as its argument and store the result in the total-sum variable.

  • Line 8: Finally, we print the total sum using the println function.

Conclusion

Therefore, the apply() function in Clojure is a flexible tool for invoking functions with various parameters. It simplifies giving a collection of arguments to a function, making your code more compact and readable. Developers leverage Clojure's functional programming model and build clean, efficient, and expressive code by knowing and efficiently using the apply() function.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved