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…
This is equivalent in clojure
Adding to dAni’s example if you need odd number sequence: