[NEXT] [PREV]    HANDBOOK / GENTLE PRIMER / Describing Computations /

# Expressions and Patterns

Gentle
Applications
Concepts
Examples
Handbook
Support

We have made a distinction between expressions and patterns, and have said that the role of a term depends on its context.

The input parameters of a predicate invocation and the output parameters of rule headings are expressions. Here, terms are constructed from given components. Variables inside the expressions must hold these components.

The output parameters of a predicate invocation and the input parameters of rule headings are patterns. Here, a given value is matched against the pattern. Variables inside the pattern are defined.

To illustrate this, we discuss a predicate swap that, given a term signal(X, Y), delivers the term signal(Y, X). It is defined by the rule

```
'rule' swap (signal(X, Y) -> signal(Y, X))
```
Assume that the variable A holds the value red and consider the invocation
```
swap (signal(A, yellow) -> signal(B, red))
```
First, the expression signal(A, yellow) (the input parameter of the invocation) is evaluated. Since A holds red, substitution yields the value signal(red, yellow).

Then, rules defining the predicate are inspected; here there is only one. The input value signal(red, yellow) is matched against the pattern signal(X, Y) (the input parameter of the rule head). The matching succeeds, thereby defining the variable X as red and Y as yellow.

Now the expression signal(Y, X) (the output parameter of the rule head) is evaluated. Since Y is yellow and X is red, this yields signal(yellow, red), which is returned by the predicate.

Finally, the returned value signal(yellow, red) is matched against the pattern signal(B, red) (the output parameter of the invocation). This succeeds and defines the variable B as yellow (see Fig. 1.1).

```INVOCATION:       swap(signal(A  , yellow) -> signal(B     , red))
|                         A
|(1)                      |(4)
V                         |
signal(red, yellow)    signal(yellow, red)
|                         A
|(2)                      |(3)
V                         |
RULE HEADING:     swap(signal(X  , Y     ) -> signal(Y     , X  ))

(1) construction of term from input expression
(2) matching against input pattern
(3) construction of term from output expression
(4) matching against output pattern
```
Fig. 1.1 Construction of Terms and Pattern Matching