6.0 Procedural Programming
6.0 Procedural Programming
Procedural programming offers a powerful strategy for managing complexity and promoting code reuse. In Logo, procedures (also known as subprograms) are a critical feature for encapsulation, allowing developers to group a sequence of commands under a single, custom name. By defining their own commands, developers can improve the readability of their code, eliminate redundancy, and build complex systems from simple, reusable components. This section covers the definition, parameterization, and recursive application of procedures, which are essential for advanced Logo programming. These abstract concepts find practical application in features like the color system.
6.1 Defining and Invoking Procedures
Procedures are named sequences of commands that can be defined once and then executed multiple times.
- Definition Syntax: A procedure is defined using the to and end keywords. The definition is typically written in the Edall editor.
- Example:
- Invocation: To run a procedure, simply type its name into the command line and press Enter.
- Example: square
6.2 Parameterization
To make procedures more flexible, they can be designed to accept arguments (or parameters). A parameter acts as a variable within the procedure whose value is supplied when the procedure is called.
- Definition with Parameters: To add a parameter, declare its name (preceded by a colon) on the same line as the procedure name.
- Invocation with Arguments: When calling the procedure, provide a value for each parameter.
- Example: square 50 will draw a square with sides of length 50.
6.3 Recursive Procedures
A recursive procedure is one that calls itself from within its own body. This technique is extremely powerful for creating complex, repeating patterns like fractals and spirals.
A recursive procedure requires two key components:
- Recursive Call: The line of code where the procedure calls itself, typically with a modified argument. In the example below, this is spiral_recur 0.95 * :n.
- Base Case: A condition that stops the recursion to prevent an infinite loop. In the example, this is if :n < 1 [stop].
Example:
to spiral_recur :n
if :n < 1 [stop]
fd :n
rt 20
spiral_recur 0.95 * :n
end