如何在Clojure中编写一个保持状态的闭包?

jaz*_*esh 3 javascript closures clojure

我想在Clojure中编写一个闭包来模拟以下JavaScript代码:

var nextOdd = function () {
    var x = 1;
    return function () {
        var result = x;
        x += 2;
        return result;
    }
}();
nextOdd(); //1
nextOdd(); //3
nextOdd(); //5
Run Code Online (Sandbox Code Playgroud)

我知道Clojure支持闭包,所以我可能会写一些类似的东西

(defn plusn [x]
    (fn [y] (+ x y)))
(def plus2 (plusn 2))
(plus2 3)
Run Code Online (Sandbox Code Playgroud)

但是我每次调用函数时都需要能保持状态(即下一个奇数的状态)的东西...然后在Clojure中有完整的不变性......

mob*_*yte 9

这相当于clojure

(def next-odd (let [x (atom -1)]
                (fn []
                  (swap! x + 2))))

(next-odd)
-> 1
(next-odd)
-> 3
(next-odd)
-> 5
(next-odd)
...
Run Code Online (Sandbox Code Playgroud)

如果您需要奇数序列,请添加到dAni的示例:

(def odd-numbers (iterate (partial + 2) 1))

(take 5 odd-numbers)
-> (1 3 5 7 9)
Run Code Online (Sandbox Code Playgroud)


Dan*_*ero 6

mobyte的回答是正确的,但你是如何试图用无限懒惰的赔率序列来解决你的问题的?(take 10 (filter odd? (range))).也许你不需要国家.