This should be a very trivial question. i am new to Clojure and writing this if-then-else based on: http://clojure.org/special_forms#Special%20Forms--%28if%20test%20then%20else?%29
However, I keep getting this error:
java.lang.Exception: Too many arguments to if (NO_SOURCE_FILE:424)
// This code has infinite recursion bugs; but it should compile!
(defn sumdown [sum x]
(
if (foo x)
(do
(recur (+ sum x) (dec x))
)
else do(
(recur (+ sum x) (dec x))
)
)
)
Clojure - If Statement. The first decision-making statement is the ‘if’ statement. Following is the general form of this statement in Clojure. Syntax. 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.
We have seen in the classic ‘if’ statement in Clojure that you can just have two statements, one which is executed for the true part and the other which is for the false part. But the ‘if-do’ expression allows you to use multiple expressions.
In Clojure, however, everything is an expression! Everything returns a value, and a block of multiple expressions returns the last value. Expressions that exclusively perform side-effects return nil. Accordingly, flow control operators are expressions, too! Flow control operators are composable, so we can use them anywhere.
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.
In the template:
(if test then else?)
both then
and else
don't represent keywords, but actual expressions. The ?
indicates the else
expression is optional.
The test condition is evaluated and based on its value, the appropriate branch expression is evaluated and "returned" as the value of the entire if expression.
For example, this would define an absolute value function:
(defn abs [x]
(if (< x 0)
(- x)
x))
(defn sumdown [sum x]
(if (foo x)
(recur (+ sum x) (dec x))
(recur (+ sum x) (dec x))))
This is the idiomatic way to write this code. I recommend a text editor / IDE with basic support for editing Lisp source (paren/bracket/brace matching).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With