Written by
Aaron Bell
on
on
How I understand Clojure's `apply`
I wrote a big ole’ post on apply
, but to save you time I’ll shrink it:
To start:
- Clojure functions work with the
AFn
class… - which implements the
IFn
interface… - which specificies twenty-two overloads of
invoke
- and a method called
applyTo
Then:
applyTo
takes a sequence- and passes it to
applyToHelper
- this counts the sequence and
- it passes it into a twenty-two branch switch statement
- which decides how much
ISeq.first
andISeq.next
ing to do - to pull out every argument into an
invoke
apply
uses applyTo
with Java interop.
(f '(1 2 3))
will run the single-arity f.invoke('(1 2 3))
. (apply f '(1 2 3))
will run the triple-arity f.invoke(1 2 3)
which is useful for things like max
, min
, distinct?
.
(max [1 2 3]) ;;=> [1 2 3]
(apply max [1 2 3]) ;;=> 3
(apply max 4 [1 2 3]) ;;=> 4 a.k.a. the "chips"
(min [1 2 3]) ;;=> [1 2 3]
(apply min [1 2 3]) ;;=> 1
(apply min 0 [1 2 3]) ;;=> 0
(distinct? [1 1 3]) ;;=> true
(apply distinct? [1 1 3]) ;;=> false
(apply distinct? 1 [1 2 3]) ;;=> false
That’s it. 🙂