Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clojure

What is variadic function in Clojure?

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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)))
Variadic function syntax

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")
Variadic function example in Clojure

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 others keyword 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.

RELATED TAGS

clojure

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring