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

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

问题描述

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

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



换句话说:如何改变引用函数的状态?我看到了一些关于变量变量的示例,但他们看不到非常漂亮的它们吗?

解决方案

不要doooo itttttt!保存自己之前太晚了!突变状态没有理由不是Clojure鼓励,所以当然不是那么方便,因为它会在通用lisp。



但是,这是一个用于解释闭包的经典例子,虽然它不是真正在Clojure中非常有用的一个例子,但很高兴知道翻译。你必须写如下:

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


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?

解决方案

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

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

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