Leon Grapenthin
Leon Grapenthin

Reputation: 9266

Implementation: Why is `reduce` not variadic

E. g. why can reduce not be used with multiple input sequences as its arguments like map, mapv?

What are the implementors/Rich Hickeys reasons behind that decision?

Would it affect performance, if so how? Is it simply language design that wants to lead us in the "right" direction, if so why?

EDIT: As found out in the discussion (with the help of @Alex), here are the overloads of a variadic reduce

([f coll])

([f val & colls]) (because an initial accumulator would be required in the variadic scenario).

So even if it was made variadic today, nothing about its current behavior would change.

Upvotes: 2

Views: 155

Answers (1)

mikera
mikera

Reputation: 106351

It already is variadic (in the sense of supporting more than one arity):

=> (doc reduce)
-------------------------
clojure.core/reduce
([f coll] [f val coll])
  f should be a function of 2 arguments. If val is not supplied,
  returns the result of applying f to the first 2 items in coll, then
  applying f to that result and the 3rd item, etc. If coll contains no
  items, f must accept no arguments as well, and reduce returns the
  result of calling f with no arguments.  If coll has only 1 item, it
  is returned and f is not called.  If val is supplied, returns the
  result of applying f to val and the first item in coll, then
  applying f to that result and the 2nd item, etc. If coll contains no
  items, returns val and f is not called.

If you made it variadic even further (e.g. allowing an arbitrary number of collections) then the 3 argument case would be ambiguous - did you mean to pass an initial value, or two different collections?

IMHO making functions variadic in more than one different aspect is something of an anti-pattern. Just because you can change the meaning of functions with arity overloads doesn't mean it is a good idea: you are often better off explicitly achieving the same effect by composing higher order functions.

Upvotes: 2

Related Questions