Scheme Programming/Simple Maths

From Wikibooks, open books for an open world
< Scheme Programming
Jump to: navigation, search

We can use combinations of the datatypes and primitive procedures to perform simple (and not so simple) calculations using the scm interpreter:

> (+ 2 2)
4
> (* 2 8)
16
> (- 2 1)
1
> (/ 3 4)
0.75

These are, in order,

  • Addition
  • Multiplication
  • Subtraction
  • Division

Each of these expressions can be nested within one another, thus:

> (+ (* 2 4) (/ 3 4) (- 2 1) (+ 2 2))
13.75

This shows 2 important things about Scheme expressions:

  • Scheme expressions can be nested, leading to an important concept, the Substitution Model.
  • Some procedures can take a variable number of arguments; we'll show how to do this later.

The first point is most important at this point.

The Substitution Model[edit]

The substitution model for computing expressions is one of the simplest and most powerful ways of thinking about Scheme expressions. It can be regarded as the basis of a large portion of Scheme.

In order to understand the substitution model, I'll give you a simple example, the one given before, and work through it.

> (+ (* 2 4) (/ 3 4) (- 2 1) (+ 2 2))

In order to evaluate this, the scheme interpreter must evaluate every sub-expression, thus decomposing it to atomic datatypes and primitives:

> (+ 8 0.75 1 4)
13.75

This same model can be applied to extra layers of nesting.

> (* (+ 13 1) (+ (* 2 4) (/ 3 4) (- 2 1) (+ 2 2)))
> (* (+ 13 1) (+ 8 0.75 1 4))
> (* 14 13.75)
192.5

The best way to think about this is as a basic algorithm.

  1. Has the expression any subexpressions?
    1. yes: Evaluate subexpressions using this algorithm
    2. no: Evaluate whole expression of primitives.