javascript - How do I write a closure in Clojure that maintains state? - Stack Overflow

I want to write a closure in Clojure to simulate the following JavaScript code:var nextOdd = function (

I want to write a closure in Clojure to simulate the following JavaScript code:

var nextOdd = function () {
    var x = 1;
    return function () {
        var result = x;
        x += 2;
        return result;
    }
}();
nextOdd(); //1
nextOdd(); //3
nextOdd(); //5

I know that Clojure supports closures so I could potentially write something like

(defn plusn [x]
    (fn [y] (+ x y)))
(def plus2 (plusn 2))
(plus2 3)

But I need something that will maintain state (i.e. the state of the next odd) every time I call the function... and then there's the whole immutability thing in Clojure...

I want to write a closure in Clojure to simulate the following JavaScript code:

var nextOdd = function () {
    var x = 1;
    return function () {
        var result = x;
        x += 2;
        return result;
    }
}();
nextOdd(); //1
nextOdd(); //3
nextOdd(); //5

I know that Clojure supports closures so I could potentially write something like

(defn plusn [x]
    (fn [y] (+ x y)))
(def plus2 (plusn 2))
(plus2 3)

But I need something that will maintain state (i.e. the state of the next odd) every time I call the function... and then there's the whole immutability thing in Clojure...

Share Improve this question asked Dec 9, 2012 at 2:16 jazzyfreshjazzyfresh 7711 gold badge6 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

This is equivalent in clojure

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

(next-odd)
-> 1
(next-odd)
-> 3
(next-odd)
-> 5
(next-odd)
...

Adding to dAni's example if you need odd number sequence:

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

(take 5 odd-numbers)
-> (1 3 5 7 9)

mobyte answer is correct, but how you tried to solve your problem with an infinite lazy sequence of odds? (take 10 (filter odd? (range))). Perhaps you don't need state.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744312822a4568034.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信