[Solved] What is the equivalence in scheme for ‘if’? [closed]


It depends. You really should try to narrow you question further with an actual problem in scheme since the answer will depend on what you are trying to do.

In idiomatic Scheme most should be done without side effects so you have

(if predicate-expression
    consequent-expression
    alternative-expression) ;; alternative is optional but should be used anyway.

But with your code you have more than one thing in the branches, something like:

int test (condition)
{
    if (condition)
    {
        function1();
        return function2();
    }
    else
    {
        function3();
        return function4();
    }
}

Here, in order for function1 and function3 to do anything useful it has to mutate, read or write something, also called a side effect. You should try to avoid that so in Scheme you either use a let to store a temporary variable, do the call so when it returns it is used like this:

(define (test condition)
  (if condition
      (let ((tmp (function3)))
        (function4 tmp))
      (function4 (function3))))

Now. You will eventually need side effects for a few procedures and then you need to use begin or use cond which has explicit begin.

(if predicate-expression
    (begin 
       consequent-side-effect-expression
       consequent-tail-expression)
    (begin
       alternative-side-effect-expression 
       alternative-tail-expression))

Now begin joins together several expressions into one and the result of a begin block is it’s last expression, thus you can even use it in the predicate. Cond has an explicit begin in every consequent so I often switch from if to cond when I either need more than one consequent or a begin:

(cond (predicate-expression  consequent-side-effect-expression 
                             consequent-tail-expression)

      (predicate2-expression consequent2-tail-expression2)

      (else alternative-side-effect-expression 
            alternative-tail-expression))

Often when there is side effects you not always need the alternative. Eg. you are actually not interested in what the if returns because it may not be in tail position either. In these cases you have in the (rnrs control (6)) library when and unless with explicit begin:

(when expression
      consequent-side-effect-expression
      ...
      consequent-tail-expression)

(unless expression
        consequent-side-effect-expression
        ...
        consequent-tail-expression)

A let or a procedure also has explicit begin:

(let ()
  (display "hello") ; displays "hello"
  5)                ; returns 5

(define (test x)
  (display x)       ; display x
  (+ x 5))          ; return x+5

solved What is the equivalence in scheme for ‘if’? [closed]