6

I am discussing closure with a friend and he thinks (partial + 5) is a closure. But I think a closure is a function closing over a free variable, for example

(let [a 10]
  (defn func1 [x] (+ x a))
)

then func1 is a closure. But in this case 5 is not a free variable. So which is the right answer?

xiefei
  • 6,563
  • 2
  • 26
  • 44
  • While the accepted answer is correct in terms of implementation, I'd argue that it shouldn't be considered a closure, but rather "just" a partial application. The use of a closure is an internal implementation detail that is not directly exposed to the caller. – user2864740 Nov 30 '13 at 20:28

2 Answers2

8

partial uses a closure to make the partial function. Check out the code of partial by using (source partial) in repl and you will see that it uses closures.

(defn partial
  "Takes a function f and fewer than the normal arguments to f, and
  returns a fn that takes a variable number of additional args. When
  called, the returned function calls f with args + additional args."
  {:added "1.0"}
  ([f arg1]
   (fn [& args] (apply f arg1 args)))
  ([f arg1 arg2]
   (fn [& args] (apply f arg1 arg2 args)))
  ([f arg1 arg2 arg3]
   (fn [& args] (apply f arg1 arg2 arg3 args)))
  ([f arg1 arg2 arg3 & more]
   (fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))
mikera
  • 105,238
  • 25
  • 256
  • 415
Ankur
  • 33,367
  • 2
  • 46
  • 72
0

(partial + 5) is an anonymous function or "lambda".

Anonymous functions are often¹ called "closures" but it's an abuse of the term ; see the discussion in "What is the difference between a 'closure' and a 'lambda'?"


[¹] Maybe because in most popular languages that support them, closures and anonymous functions are created using the same language features - which renders them undistinguishable at first glance.

Community
  • 1
  • 1
omiel
  • 1,573
  • 13
  • 16