Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure if-then-else?

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))
     )

     )
) 
like image 779
Asad Iqbal Avatar asked Dec 24 '11 03:12

Asad Iqbal


People also ask

How do you use if statements in Clojure?

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.

What is the ‘if-do’ expression in Clojure?

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.

Is Everything an expression in Clojure?

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.

What is a condition 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.


2 Answers

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))
like image 135
jacobhaven Avatar answered Oct 22 '22 16:10

jacobhaven


(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).

like image 42
dnolen Avatar answered Oct 22 '22 17:10

dnolen