Recursion

Recursion is a technique seen frequently in procedural modeling. It is typically used when modeling "fractal" or self-similar forms.

A New Way to Count

Below is a simple example of a procedure which will count from a low number to a high number:

(define (count low high)
 (while (<= low high)
  (begin
   (print low)
   (set! low (+ low 1))
   )))
This is iteration, as we used to model flowers in previous examples.

Alternatively, we could use recursion to accomplish the same task. It looks almost the same, but with two major differences:

(define (count low high)
 (if (<= low high)
  (begin
   (print low)
   (count (add1 low) high)
   )))
The "while" has changed to an "if", and the increment of "low" has changed to a call to the function itself.

Making Trees

The reason for such a seeming twisted algorithm can be seen if we try to model a simple two dimensional (binary) tree like the one below. We are hard pressed to create a short iterative function to accomplish the task. But recursively it is easy.

Source Code

One small change will add leaves to the ends of the branches. At the lowest level of recursion, when the "if" condition fails, we have it return a leaf for its "else" value:

Source Code

The tree can be extended to 3D by rotating branches out of the plane. A more complex and realistic tree is created by using more than two branches at each branch point, and varying transformations stochastically.

Source Code


Triangle Example

Source Code

Note that this same technique could be used to break up space in volume, to generate rooms in a building, for example.

Mountain Example

Here's a simple example where several fractal triangles have been combined to make a pyramidial mountain.
(world
 (define level 6)
 (frac-tri #<1 0 1> #<-1 0 1> #<0 1 0> 1 level 5 2)
 (frac-tri #<-1 0 1> #<-1 0 -1> #<0 1 0> 1 level 5 2)
 (frac-tri #<-1 0 -1> #<1 0 -1> #<0 1 0> 1 level 5 2)
 (frac-tri #<1 0 -1> #<1 0 1> #<0 1 0> 1 level 5 2)
 )


Growth Simulation

Making the branching degree sensitive to time combined with some clever scaling can simulate growth:

Source Code


Return to Schedule Information
mrl