在 Clojure 中编写累加器函数 [英] Writing an accumulator function in Clojure

查看:25
本文介绍了在 Clojure 中编写累加器函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何编写书呆子的复仇文章中包含的累加器示例.很容易理解它的工作原理,但是我没有在 Clojure 中重新创建它 - 它不会累积,而只是返回 i 和 n 的初始给定值的总和.

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.

键位于 incf(在 Common Lisp 版本中)或 +=(在 JavaScript 中).

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?

推荐答案

不要乱说!在为时已晚之前拯救自己!Clojure 不鼓励无缘无故地改变状态,所以当然它不像普通 lisp 那样方便.

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.

但说真的,这是一个解释闭包的经典示例,虽然它在 Clojure 中并不是非常有用,但了解翻译还是很高兴的.您必须编写如下内容:

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))))

这篇关于在 Clojure 中编写累加器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆