What is variadic function in Clojure?
What is a function?
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 run time or execution time of the application.
What is a variadic function?
A variadic function is one that receives a varying number of parameters. Unlike a normal function, in which we indicate the number of parameters and cannot exceed the number of passed parameters, in a variadic function, we can pass a single parameter during the declaration of the function and accept more than one while calling it.
Syntax
(defn variadic[arg1 & others](code block)))
Parameters
The variadic function must have at least one parameter on declaration followed by an & (ampersand) and the keyword others. Let's see an example to explain this further.
Example
(ns clojure.examples.example(:gen-class))(defn example[arg1 & others](println (str arg1 (clojure.string/join " " others))))(example "Hard " "Work" "Pays")
Code explanation
In the code above, we are trying to join multiple strings together to form a sentence. Look up the shot on the string join method.
Line 3: We declare the function example.
Line 4: We pass the parameter as explained in the Parameters section.
Line 5: We do multiple things here:
- We print multiple strings joined together using
println.
- We carry out a string operation (thus needing the
str). - We pass our first parameter
arg1. - We call the join method
clojure.string/join. - We pass the
otherskeyword after the" ". This will enable us to pass a varying number of parameters when the function is called.
Line 6: We pass our parameter into the called function, as follows: (example "Hard" "Work" "Pays"). This executes and prints the joined strings.