Below is quick run down of what we covered in the workshop. We present the syntax and a few examples. It should s erve as a reminder or 'cheat sheet'.
; A comment
Anything from a semicolon to the end of a line is ignored by the Scheme intrepreter. We'll use comments to show the results of running Scheme expressions.
(operator arg ...)
The most basic form. The operator always comes first, followed by the arguments (if there are any). For example:
(+ 1 1) ;2 (* (+ 2 1) 3) ;9
Note you work from the innermost parentheses out.
(define (name arg ...) body ...)
Defines a function called name
that takes the arguments
arg ...
. For example:
;; Contract: ;; square : number -> number ;; ;; Purpose: ;; Squares a number ;; ;; Example: ;; (square 2) = 4 (define (square x) (* x x))
We can use square like any other operator:
(square 4)
8
Note the comments we've used to describe the function. It's good practice to do all of this. At the least the contract of the function should be specified.
(< num1 num2) (<= num1 num2) (> num1 num2) (>= num1 num2)
Scheme has the usual conditional operator, which return true
(written #t
) and false (written #f
). E.g.:
(< 2 3) ;\#t (<= 3 3) ;\#t (> 1 4) ;\#f (>= 3 3.05) ;\#f
We call #t
and #f
booleans.
(if condition true-expression false-expression)
An if
allows you to selectively evaluate an expression depending on a
condition. If the condition is true, the true expression is
evaluted. Otherwise the false expression is evaluated. For example,
to define a function that return the absolute value of a number:
;; Contract: ;; abs : number -> number ;; ;; Purpose: ;; Compute the absolute value of a number ;; ;; Example: ;; (abs -1) = 1 (define (abs x) (if (>= x 0) x (* x -1)))
(cond [(test expr)] [(test expr)] ...)
The cond
form allows to write a load of test conditions.
The first test to be true has its associated expression evaluated.
cond
is a convenient way to write a load of if
s.
For example:
;; Contract: ;; sign : number -> number ;; ;; Purpose: ;; Compute the sign function: ;; if x > 0, sign(x) = 1 ;; if x = 0, sign(x) = 0 ;; if x < 0, sign(x) = -1 ;; ;; Example: ;; (sign -123) = -1 (define (sign x) (cond [(> x 0) 1] [(= x 0) 0] [(< x 0) -1]))
Note that square brackets ([]) mean the same a parentheses. We use
them as they visually distinguish the different clauses of the
cond
form. The same function written using if
looks
like:
(define (sign x) (if (> x 0) 1 (if (= x 0) 0 -1)))
The cond
version is much clearer!
In case you're wondering why you'd want a function like sign
it's sometimes used in artificial neural networks.