Atoms
The building blocks of Scheme programs are atoms and lists. Atoms are single objects, and can be either identifiers or literals:
Code: Select all
; comments begin with semi-colons and go to the end of the line.
An-Atom ; the identifier 'An-Atom'
1234 ; the integer '1234'
17/23 ; the rational number seventeen twenty-thirds
3.14 ; the exact rational number 3.14
#i3.14 ; an inexact real number approximating 3.14
#\a ; the character 'a'
"Hello, World!" ; the string "Hello, World!"
#t ; special atom for the boolean value 'true'
#f ; special atom for the boolean value'false'
Lists
A list is a group of one or more atoms in a pair of parentheses (most versions allow you to substitute brackets or even braces for parentheses, so long as each member of a pair matches the other). For example,
Code: Select all
(a b c)
Code: Select all
((a) (b c) d)
Another key concept in Scheme is that code is represented the same way as data, and that data can be evaluated as code. When a Scheme interpreter reads a list, it tries to interpret the first value in the list as a function call. For example,
Code: Select all
(list 1 2)
Code: Select all
(1 2)
With a handful of exceptions, all Scheme operations are performed in the form of a function call. For example, to add 2 to 3, you would write:
Code: Select all
(+ 2 3)
Code: Select all
(/ (- 3 #i3.14) (* (+ 1000 56) 5))
Code: Select all
(/ (- 3 #i3.14)
(* (+ 1000 56)
5))
Define
A special form, (define), exists to assigning a value of an identifier. It can be used both for initializing variables and for defining functions. Given the following definitions,
Code: Select all
(define one 1)
(define (inc x) (+ one x))
Evaluation and Quoting
When the interpreter reads an identifier, by default it tries to evaluate it, either as a function name if it is at the beginnning of a list, or otherwise as a variable. For example, given the example above, entering 'one' at the interpreter prompt would return '1'.
> one
1
While a list starting with 'inc' would be evaluated in this manner, if one were to trace the evaluation:
> (inc one)
---> (inc 1)
---> (+ one 1)
---> (+ 1 1)
2
This evaluation can be overriden using the (quote) special form:
Code: Select all
(quote a)
Code: Select all
'a
Code: Select all
(define one 1)
(define two 2)
(define (square x)
(* x x))
> (list one two (square two))
(1 2 4)
but if you quote the atoms, the result is
>(list 'one 'two '(square two))
(one two (square two))
(Note that if you are using DR Scheme, the '"Beginner Student" language subset doesn't support quoting lists, but "Advanced Student" and "Standard (R5RS)" do).
I'll add more later, but this should make a good start. I'll cover conditionals, predicates and recursion next, then the list manipulation functions. I'm not sure what else I'll add. Eventually I'll discuss mutators (set!, set-car!, etc.), but they aren't really as important in Scheme as it is in most other languages.