How to increment by a number in Clojure?

2020-07-10 07:04发布

问题:

I would like to know how to increment by X amount a number, in other languages I used to do

foo += 0.1;

but I have not idea how it can be done in Clojure

回答1:

Variables are immutable in Clojure. So you should not try to change the value of foo, but instead, "create" a new foo:

(def foo2 (+ foo 0.1))

...or, if in a loop, recur with a new value:

(loop [foo 5.0]
  (when (< foo 9)
    (recur (+ foo 0.1))))

...or, if foo is an atom, swap! it with a new value:

(def foo (atom 5.0))
(swap! foo (partial + 0.1))

I recommend you start by reading the rationale of Clojure.



回答2:

Blacksad's answer covers defining vars so I would just like to add the other scopes in which you may wish to have a value that is incremented from another value:

within a function's local scope:

user> (defn my-function [x]
        (let [y (inc x)
              z (+ x y)]
          [x y z]))
#'user/my-function
user> (my-function 4)
[4 5 9]

and If you want to build a value incrementally to make the process more clear:

user> (defn my-function [x]
        (let [y (inc x)
               z (+ x y)
               z (+ z 4)
               z (* z z)]
          [x y z]))
#'user/my-function
user> (my-function 4)
[4 5 169]

This can make the process more presentable, though it is not a "way to get variables back" and is really only useful in limited contexts. This pattern is used in clojure.core's threading macros.



标签: clojure