If Else in Scheme

Branching with if and else in Scheme is straightforward.

(define (main)
  ; Here's a basic example.
  (if (= (remainder 7 2) 0)
      (display "7 is even\n")
      (display "7 is odd\n"))

  ; You can have an if statement without an else.
  (when (= (remainder 8 4) 0)
    (display "8 is divisible by 4\n"))

  ; Logical operators like 'and' and 'or' are often useful in conditions.
  (when (or (= (remainder 8 2) 0) (= (remainder 7 2) 0))
    (display "either 8 or 7 are even\n"))

  ; In Scheme, we can use let to bind variables before a conditional.
  (let ((num 9))
    (cond ((< num 0) (display (string-append (number->string num) " is negative\n")))
          ((< num 10) (display (string-append (number->string num) " has 1 digit\n")))
          (else (display (string-append (number->string num) " has multiple digits\n")))))
)

(main)

To run the program:

$ scheme < if-else.scm
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

In Scheme, the if special form is used for basic conditional branching. It takes three arguments: a condition, a consequent (executed if the condition is true), and an alternative (executed if the condition is false).

For conditions without an else clause, Scheme provides the when special form, which is equivalent to an if without an else.

Logical operators in Scheme are and and or, used similarly to their counterparts in other languages.

Scheme doesn’t have a direct equivalent to Go’s ability to declare variables in an if statement. However, we can use let to bind variables before a conditional block.

For more complex conditional branching, Scheme provides the cond special form, which allows for multiple conditions and associated actions.

Note that in Scheme, you don’t need parentheses around conditions, but the entire if, when, or cond expression must be enclosed in parentheses.