Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is this partial function a closure?

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?

like image 854
xiefei Avatar asked Jul 19 '12 09:07

xiefei


1 Answers

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)))))
like image 102
Ankur Avatar answered Nov 15 '22 09:11

Ankur