scheme S-Expression


An expression in Scheme is what is going to get executed. A S-expression, as it's usually called starts with a ( and end with a ). The first member of the expression is what is going to get executed. The following member of the expression are the parameters that will be sent to the expression during the evaluation of the expression.

For example adding numbers:

(+ 1 2 3)

In this case, + is a symbol to a add function that takes multiple parameters. 1, 2 and 3 are sent to the + function.

S-Expression may contain S-Expressions as parameters as shown in the following example:

(if (< x y)

Which can be read as if x is less than y return x else return y. In this example we evaluate the condition expression, depending on the resolved value, either x or y will be returned. It could be evaluated to this

(if #t x y)
(if #f x y)

A less obvious example for beginners is to have a S-Expression as part of the first member of a S-Expression. This way, we can change the behaviour of a method by changing the function that will be called without having to create branches with the same parameters. Here's a quick example of an expression that either add or substract numbers if x is below y.

((if (< x y) + -) 
  1 2 3)

If x is below y, the expression will be evaluated as:

(+ 1 2 3)


(- 1 2 3)

As you can see, Scheme allow the programmer to build up complex piece of code while giving the programmer the tools to prevent duplicating code. In other languages we could see the same example written as such:

(if (< x y) (+ 1 2 3) (- 1 2 3))

The problem with this method is that we duplicate a lot of code while the only thing that change is the method being called. This example is fairly simple but with more condition we could see a lot of similar lines duplicated.