Scheme Programming/Simple Maths

< Scheme Programming

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,

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:

The first point is most important at this point.

The Substitution Model

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.
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.