Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i++ equivalent in Clojure

Tags:

clojure

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 there any shortcuts?

like image 332
Enrique Avatar asked Dec 22 '10 19:12

Enrique


People also ask

How do you check for equality in Clojure?

Equality in Clojure is most often tested using = . Unlike Java's equals method, Clojure's = returns true for many values that do not have the same type as each other. = does not always return true when two numbers have the same numeric value.

How do you do if else in Clojure?

In Clojure, the condition is an expression which evaluates it to be either true or false. If the condition is true, then statement#1 will be executed, else statement#2 will be executed. The general working of this statement is that first a condition is evaluated in the 'if' statement.

Does Clojure have closures?

Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.

How do you return a function in Clojure?

Functions Returning Functions and Closures Our first function will be called adder . It will take a number, x , as its only argument and return a function. The function returned by adder will also take a single number, a , as its argument and return x + a . The returned function form adder is a closure.


1 Answers

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

like image 74
lurscher Avatar answered Sep 22 '22 11:09

lurscher