16
votes

I had a pretty simple requirement in my Scheme program to execute more than one statement, in the true condition of a 'if'. . So I write my code, something like this:

(if (= 1 1)
 ((expression1) (expression2))  ; these 2 expressions are to be
                                ; executed when the condition is true
  (expression3))

Obviously, the above doesn't work, since I have unintentionally created a # procedure with # arguments. So, to get my work done, I simply put the above expressions in a new function and call it from there, in place of the expression1, expression2. It works.

So, my point here is: is there any other conditional construct which may support my requirement here?

5

5 Answers

23
votes

In MIT-Scheme, which is not very different, you can use begin:

(if (= 1 1)
    (begin expression1 expression2)
    expression3)

Or use Cond:

(cond ((= 1 1) expression1 expression2)
      (else expression3))
2
votes

(begin ...) is how you evaluate multiple expressions and return the last one. Many other constructs act as "implicit" begin blocks (they allow multiple expressions just like a begin block but you don't need to say begin), like the body of a cond clause, the body of a define for functions, the body of a lambda, the body of a let, etc.; you may have been using it without realizing it. But for if, that is not possible in the syntax because there are two expressions (the one for true and the one for false) next to each other, and so allowing multiple expressions would make it ambiguous. So you have to use an explicit begin construct.

1
votes

you can use (begin ...) to get what you want in the true branch of your if statement. See here

1
votes

You can use COND, or put the expressions into something like PROGN in Lisp (I am not sure how it is called in PLT Scheme. edit: it is called BEGIN).

COND looks like this in Scheme:

(cond [(= 1 1)
       (expression1)
       (expression2)]
      [else
       (expression3)])
0
votes

Using an if statement with more than two cases involves nesting, e.g.:

(if (test-1)               ; "if"
    (expression-1)
    (if (test-2)           ; "else-if"
        (expression-2)
        (expression-3)))  ; "else"

Using cond seems to be the preferred way for expressing conditional statements as it is easier to read than a bunch of nested ifs and you can also execute multiple statements without having to use the begin clause:

(cond ((test-1)
       (expression-1))
      ((test-2) 
       (expression-2)
       (expression-3))
      (else 
       (default-expression)))