Writing an accumulator function in Clojure

徘徊边缘 提交于 2019-12-01 01:25:34

问题


I'd like to know how to write the accumulator example included in the Revenge of the Nerds essay. It's easy to understand how it works, however I fail to recreate it in Clojure - it doesn't accumulate but just returns the sum of i and the initial given value of n.

The key is in incf (in the Common Lisp version) or += (in JavaScript).

In other words: how to alter the state of a referenced function? I've seen some examples on mutating variables but they don't look precisely pretty do they?


回答1:


Don't doooo itttttt! Save yourself before it's too late! Mutating state for no reason is not something Clojure encourages, so of course it's not as convenient as it would be in common lisp.

But seriously, this is a classical example for explaining closures, and while it isn't one that really is very useful in Clojure, it's nice to know the translation. You would have to write something like:

(defn foo [n]
  (let [acc (atom n)]
    (fn [i] (swap! acc + i))))


来源:https://stackoverflow.com/questions/8442524/writing-an-accumulator-function-in-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!