Here's an issue I keep running into in Clojure:
user=> (max [3 4 5 6 7])
[3 4 5 6 7] ; expected '7'
Some functions don't do what I expect!
Here's one solution using apply
:
user=> (apply max [3 4 5 6 7])
7
Other examples are concat
, and min
.
My question, as a Clojure newbie, is why are these functions variadic? I expected them to operate on sequences. Is using apply
the best/idiomatic way to get what I want?
Note: I'm not trying to say that it's bad to have variadic functions, or that there is a better way. I just want to know if there's a rule or convention being followed, or if there are specific advantages to such an approach that I should be aware of.
Edit: I think the original question was unclear. Here's what I meant:
In other programming languages I've used, there are monoid-like operations, such as adding numbers, finding the greater element, concatenating lists.
There are often two use cases for these operations:
1) combining two elements, using a function that accepts two arguments
2) combining 0 to n elements, using a function that accepts a list (or sequence) of elements
A function for the second case can be built from that for the first case (often using reduce
).
However, Clojure adds a third use case:
3) combining 0 to n elements, using a variadic function
So the question is, why does Clojure add this third case?
Paul's answer indicates that:
- this allows code that is more flexible
- there are historical forces at work