Scheme R7RS Part 4: Conditionals

written by Andreas Schipplock
Now that I know a bit about numbers and strings I can go on with conditionals.

The not conditional
  > (not (= 1 2))
  #t
  > (not #t)
  #f
  > (not (= 1 1))
  #f

The and conditional
  > (and (= 1 1) (> 2 1))
  #t
  > (and #t #t)
  #t
  > (and #f #f)
  #f
  > (and #t #f)
  #f

The or conditional
  > (and (or (= 1 1) (= 2 2)) (= 1 2))
  #f
  > (and (or (= 1 1) (= 2 2)) (= 1 1))
  #t
  > (define height 100)
  #undefined
  > height
  100
  > (and (or (= height 100) (= height 200)) (= height 100))
  #t
  > (and (or (= height 101) (= height 200)) (= height 100))
  #f

The if conditional
  > (if (> 3 2) 'yes 'no)
  yes
  > (if (> 2 3) 'yes 'no)
  no

The when conditional
  (import (scheme base))
  (define height 100)
  (when (= height 100)
    (write-string "height is correct")
    (newline)
    (write-string "let's build the building")
    (newline))

This one confused me at first; I thought "when" is just a different "if", but it isn't. "When" the expression after "when" evaluates to "true" all following expressions are executed; there is no "else" here :).

The unless conditional
  (import (scheme base))
  (define height 90)
  (unless (= height 100)
    (write-string "the height is not 100")
    (newline)
    (write-string "calling the police")
    (newline))

The cond conditional The cond-conditional is a nicer version of if then else if else if else if...
  > (cond ((> 3 2) 'greater))
  greater
  > (cond ((string=? "foo" (string #\f #\o #\o)) 'yup))
  yup

  (import (scheme base))
  (cond ((= (* 2 10) 20) (write-string "2*10 is 20")
         (> (* 2 10) 10) (write-string "2*10 is > 10"))
        (else (write-string "everything before evaluated to false")))

  (newline)

  (cond ((= (* 2 10) 21) (write-string "2*10 is 20")
         (> (* 2 10) 20) (write-string "2*10 is > 20"))
        (else (write-string "everything before evaluated to false")))

  (newline)

results in:
  2*10 is 202*10 is > 10
  everything before evaluated to false

The import is necessary as I wanted to use write-string. If you are inside the repl this import was automatically done for you. If you want to put it into a script, you will need the import.

Ok, next time I will play with "Pairs and lists". Enough conditionals for now :).