You are currently browsing the tag archive for the ‘expressions’ tag.

Pretty basic stuff in these sections, but it explains some very important concepts and syntax, namely the idea of abstraction via the define statement.

1.1.1 Expressions

A programming language allows you to combine simple expressions to form more complex ideas. To do this it has three important mechanisms:

  1. Primitive expressions which represent the simplest entities
  2. Means of combination to build compound elements from simpler ones
  3. Means of abstraction to name compound elements and treat them as primitives

One kind of primitive expression in Scheme is a number. When you type an expression into the Scheme interpreter, the interpreter responds by evaluating the expression and printing its value, for example

> 486
486

I’ll use the convention that an expression prefixed by > is something that you type at the interpreter prompt, and the next line is the interpreter’s response. We form compound expressions using prefix notation, for example

> (+ 5 2)
7
> (- 10 7)
3
> (* 6 9)
63

These expressions are called combinations or S-expressions. The leftmost element is the operator, and the other elements are the operands. The value of the expression is obtained by applying the procedure specified by the operator to the arguments, which are the values of the operands.

Scheme used prefix notation, which looks unfamiliar at first but is just as valid as the standard infix notation, written 5 +2 or 10 - 7. In fact, it can have advantages, for example when procedures take an arbitrary number of arguments:

> (+ 10 7 3 5)
25

We can also easily nest combinations:

> (+ (* 4 2) (- 10 7))
11

1.1.2 Naming and the environment

None of this would be useful without the ability to give names to complex expressions, and refer to them by name later. For example, we can define the name radius to refer to a specific value by using the keyword define

> (define radius 10.0)

We could also define the value of a useful mathematical constant:

> (define pi 3.14159)

We can combine our names to make more complex expressions:

> (define area (* pi radius radius))
> area
314.159

To implement this ability to name expressions and refer to them later, the interpreter must have some way of associating names to values. This mapping is called the environment, or more accurately an environment, since we will see later that a computation may involve many different environments.