Reputation: 3321
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))
)
)
)
Upvotes: 13
Views: 19426
Reputation: 39
The correct implementation of your sample, removing all redundant code, would be:
(defn sumdown
[sum x]
(recur (+ sum x) (dec x)))
Because both your 'then' and 'else' clauses are identical and the 'do's are redundant (and in any case the various 'do' forms are for side-effects).
Other conditionals to consider are: when, cond, condp and case.
Upvotes: 1
Reputation: 18556
(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).
Upvotes: 7
Reputation: 393
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))
Upvotes: 17