Tymless Tutorial: Control



   
  < user functions

Recursion

 
routines >
 

Drawing

Control

Data

Reference

 

Functions can call other functions. They can even call themselves, in which case the call is 'recursive'. Recursion also happens if one function calls another which then calls the first again. Now in most programming languages recursion is a nifty but rarely used feature. When it is used, you have to be careful the recursion doesn't just keep on happening until the computer runs out of resources (known as an 'infinite loop'). Tymless is different. Recursion is commonplace, and Tymless takes care of it for you.

Recursive graphics generally mean fractals, although recursion can also be used for tesselation. Here is the famous Koch snowflake:

// the Koch snowflake
$>=$pi/3
{ side() >*2 side() <*2 side() }

side: side() < side() >*2 side() < side()
side: ^

The first line uses the system variable $> to tell the turtle to turn 60 degree angles rather than right-angles.

The next line sets up the irregular polygon, which contains three sides initially.

The next line defines one of two 'side' functions. It calls itself recursively four times, turning the turtle between each call.

The last line defines a second 'side' function which just tells the turtle to walk one unit and draw a corner.

When two functions are declared with the same name, the first acts as a 'generator', and the second acts as an 'initiator'. Whenever the function is called, the generator code will be run, until the program hits its recursion limit, at which point the initiator will be called instead. If there is no initiator the program will simply ignore the last call.

What is the recursion limit? Well by default this is set to 1, so as it stands our snowflake program produces a very simple looking snowflake. The generator is just called once before it starts to call the initiator. The recursion limit can be changed though, using the $limit (or $l) system variable. Here is the same snowflake run with $limit=6

In the Koch snowflake the initiator is a simple corner command, but that is not always the case. The gallery contains images in which the initiator is an irregular polygon. Tymless even lets you create initiators which are themselves recursively drawn (see routines).

 

   
  < user functions
 
routines >