An Introduction to Collective Algorithmic Music Composition

An Introduction to Scheme: Conditional Expressions and Equivalence

Logical Operators

Like most programming languages, Scheme supports the basic logical operators.

; AND operator
(and #t #t)
; => #t

; OR operator
(or #f #t)
; => #t

; NOT operator
(not #t)
; => #f

Conditional Expressions


The most common and popular way to represent a conditional expression is through an if. If the expression is true, it will return the subsequent expression, else it will return the second.

;if 4 is less than 3 return "4 is less than 3"
;else, return "4 is greater than 3"
(if (< 4 3) 
    "4 is less than 3"
    "4 is greater than 3")


Another useful way of representing conditional expressions is through cond. cond differs from an if because it allows for multiple expressions.

; cond example
(define (cond-ex x y)
    (cond ((= x y) "x equals y")
          ((< x y) "x is less than y")
          (else "x is greater than y"))) 

(cond-ex 3 2)
; => "x is greater than y"

(cond-ex 3 3)
; =>"x equals y"

(cond-ex 2 3)
; => "x is less than y"



To compare integers and floating point numbers use the = operator.

(= 2 2)


To compare same objects in memory (pointers) use the eq? predicate.

(define x 'unique)
(eq? x 'unique)


To compare values use the eqv? predicate. Unlike eq?, eqv? makes finer distinctions when comparing numbers. eqv? may also behave differently from eq? on empty vectors and empty strings.


To compare data structures such as lists, vectors and strings use the equal? predicate.

(equal? (list 1 2 3) (list 1 2 3))

eq? vs eqv? vs equal?

The following table compares the results of Scheme's equivalence procedures:

Value 1 Value 2 eq? eqv? equal?
1 1 #t #t #t
1 1.0 #f #f #f
(list 1 2) (list 1 2) #f #f #t
(lambda () 'a) (lambda () 'a) #f #f #t
() () #t #t #t
'foo 'foo #t #t #t