4.0 Advanced Programming Techniques
4.0 Advanced Programming Techniques
Logo provides structures for creating more sophisticated and reusable code.
4.1 Procedures
Procedures (also known as subprograms or functions) allow a collection of commands to be encapsulated and given a name.
- Definition: A procedure begins with the keyword to followed by the procedure name, and concludes with the keyword end. The Edall button or command opens a text editor for defining procedures.
- Execution: Once defined, a procedure can be run by typing its name in the command line (e.g., square).
- Arguments: Procedures can accept input values, or arguments, making them more versatile. An argument is declared with a colon in the definition line (e.g., to square :n). When the procedure is called, a value for the argument is provided (e.g., square 50).
4.2 Recursive Procedures
A recursive procedure is one that includes a call to itself within its own definition. This technique is powerful for solving problems that can be broken down into smaller, self-similar sub-problems. A recursive procedure must have a “stop” condition to prevent it from running indefinitely.
Example from source:
to spiral_recur :n
if :n < 1 [stop]
fd :n
rt 20
spiral_recur 0.95 * :n
end
4.3 Randomization
The random command introduces unpredictability into programs. It takes a single integer argument and returns a randomly chosen integer between 0 and one less than the argument’s value. For example, random 360 will produce a value from 0 to 359.