Alex Rivera | Logout

Is there a possibility of multiple statements inside a conditional statement's body?

Asked 2012-06-29T14:10:38.147
28

I'm primarily a C++ (thus an OO/imperative) programmer and I find it quite bizarre that you can only have one statement per evaluation in a conditional statement such as an if-statement in Scheme, a functional language.

For example:

 (let ((arg1 0) (arg2 1))
   (if (> arg1 arg2)
       arg1
       arg2)))

Erroneous example:

(let ((arg1 0) (arg2 1))
  (if (> arg1 arg2)
      (arg1 (display "cool"))
      (arg2 (display "not cool"))))

gives me an error of a type "procedure application: expected procedure, given: 2; arguments were: #void"

That can be solved by placing that said conditional statement into different statements within a body of a defined function for example, with the conditional statement's body having separate statements every time as follows:

(if (condition) statement1a statement2a)
(if (condition) statement1b statement2b)

and so on...

It goes without saying that it's not too practical. Not to mention the duplicated code overhead.

Am I missing anything here or is there really no other way?

Edit
Report

1 Answer

7

@RajeshBhat gave a good example of using begin with an if statement.

another solution is the cond form

(let ([arg1 0] [arg2 1])
  (cond
    [(< arg1 0) (display "negative!")]
    [(> arg1 arg2) (display arg1) (newline) (display "cool")]
    [else (display arg2) (newline) (display "not cool")]))

Each line in the cond form has an implicit begin which you can actually see if you look at the implementation of the cond.

(link is to the Chez Scheme documentation, might (read: probably) not be same implementation you are using as it is proprietary, though Petite Chez is free (no compiler in petite version))

http://scheme.com/tspl4/syntax.html#./syntax:s39

Edit: Important note about begin forms and therefore all expressions that have implicit begin's.

the following code

(+ 2 (begin 3 4 5))

evaluates to 7. This is because the return value of a begin form is its last expression. This is just something to keep in mind when using begins. However, using side-effects and things like displays will work just fine in the positions where the 3 and 4 are.

answered 2012-06-29T14:57:00.663

Your Answer