Clojure 如何将函数作为参数传递
我有一个函数,它接收一个向量并对所有元素求和Clojure 如何将函数作为参数传递,clojure,functional-programming,Clojure,Functional Programming,我有一个函数,它接收一个向量并对所有元素求和 (def rec (fn [numbers acc] (if (empty? numbers) acc (recur (rest numbers) (+ acc (first numbers)))))) (prn (rec [1 2 3] 0)) 但我不想调用函数“+”,而是想将操作作为参数传递,这意味着,我想将函数作为参数传递,然后调用函数 我试过: (def rec (fn [f numbers acc]
(def rec
(fn [numbers acc]
(if (empty? numbers)
acc
(recur (rest numbers) (+ acc (first numbers))))))
(prn (rec [1 2 3] 0))
但我不想调用函数“+”,而是想将操作作为参数传递,这意味着,我想将函数作为参数传递,然后调用函数
我试过:
(def rec
(fn [f numbers acc]
(if (empty? numbers)
acc
(recur (rest numbers) (f acc (first numbers))))))
(prn (rec + [4 2 1] 0))
但它不起作用,我知道有更好的方法来求向量中的数的和,但我从泛函开始,所以做这种练习很重要
提前谢谢 在这种情况下,需要使用与参数向量相同的参数重复出现:
(recur f (rest numbers) (f acc (first numbers))))))
(顺便说一句,使用
defn
定义函数是标准的,(defn f[x]…)
比(def(fn[x]…))
我认为,更具意识形态的Clojure在这里使用reduce
(defn rec [f numbers acc]
(reduce f acc numbers))
(rec + [1 2 3] 0)
# 6
保理
在你的
(def rec
(fn [numbers acc]
(if (empty? numbers)
acc
(recur (rest numbers) (+ acc (first numbers))))))
。。。您可以将累加器acc
推到rec
表面下方:
(defn rec [numbers]
(loop [ns numbers, acc 0]
(if (empty? ns)
acc
(recur (rest ns) (+ acc (first ns))))))
比如说,
(rec + [1 3])
; 4
如果要将该操作作为参数传递,约定是不带参数调用该操作将给出其标识:当将另一个参数应用于两个参数时,该值将返回另一个参数
因此
因此,我们可以将参数化的rec
编写为
(defn rec [op numbers]
(loop [ns numbers, acc (op)]
(if (empty? ns)
acc
(recur (rest ns) (op acc (first ns))))))
这几乎就是
reduce
的工作原理,虽然没有那么优雅,我想。我刚刚意识到这一点。非常感谢你,迭戈。谢谢你对函数定义的建议。标识正确吗?@renainresmartins从缩进/对齐/格式化的角度来看,您的代码是完美的。正如您所看到的,rec
函数的作用与reduce
相同,但属性顺序已更改
(defn rec [op numbers]
(loop [ns numbers, acc (op)]
(if (empty? ns)
acc
(recur (rest ns) (op acc (first ns))))))