开发者

i++ equivalent in Clojure

开发者 https://www.devze.com 2023-02-01 08:05 出处:网络
I\'m new to Clojure. Is there a shortcut to increment a variable in Clojure? In many languages this would work:

I'm new to Clojure.

Is there a shortcut to increment a variable in Clojure?

In many languages this would work:

i++;
i += 1;

In Clojure, I can do:

(def i 1)    
(def i (+ i 1))

Is this the correct way of incrementing a binding in Clojure?

Are开发者_如何学Python there any shortcuts?


You can write (inc i) to increment an integer or long.

(def i 1)
(def i+1 (inc i))

If you need to assign (inc i) to i itself, then please tell why you want to do that. There will be a more elegant (or idiomatic) solution in clojure in most of the cases.


You can use an atom and swap its value,


(let [i (atom 0)]
  (println @i)
  (swap! i inc)
  (println @i))

will give you

0
1


you can't assign to i a new value in clojure, or any other lisp, for what it matters. i will in the current context will have one and only one value. (inc i) returns a new value that might or might not be binded to a new local variable.

This is the reason why in lisp languages, tail-recursion optimization is so important; because the only way to emulate a loop is with recursion, where on each function invocation the index has a new value. tail-recursion optimization avoids one to exhaust the stack with a really long loop, by converting the recursing in a flat good old loop

clojure gives guarantees that tail-recursion optimizations will happen by using the recur function to invoke the same function again. If tail-recursion optimization is not possible, recur will give a compile-time error

Edit This is the essence of inmutability idioms. There is a strong connection between inmutability and functional-style programming. The reason is that functional programming means "code without side-effects", or to be precise, the only influence of a function in a computation is through its return value. A way to achieve that is making parameters and variables inmutables by default in the sense above. Although by now from the other posters you realise that there are ways around this and not rely on inmutability in clojure

0

精彩评论

暂无评论...
验证码 换一张
取 消