Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment by a number in Clojure?

Tags:

clojure

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

like image 823
Ricardo Sanchez Avatar asked Mar 26 '13 20:03

Ricardo Sanchez


2 Answers

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.

like image 94
Blacksad Avatar answered Nov 19 '22 23:11

Blacksad


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.

like image 21
Arthur Ulfeldt Avatar answered Nov 19 '22 21:11

Arthur Ulfeldt