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 badges2 Answers
Reset to default 9This 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条)