2. Cloning Your Turtle’s Skills: Creating with Procedures
- Cloning Your Turtle’s Skills: Creating with Procedures
Procedures are one of the most powerful tools for organizing your code. They allow you to define your very own custom commands in Logo. Think of a procedure as a recipe. You write the recipe (the steps from to to end) once. Then, anytime you want to make that dish, you just say its name (square) instead of re-reading all the steps.
The Power of Procedures
Procedures make code cleaner, easier to read, and reusable. Compare drawing a square the repetitive way versus the procedure way.
The Repetitive Way You have to type the same commands over and over:
fd 100 rt 90 fd 100 rt 90 fd 100 rt 90 fd 100 rt 90
The Procedure Way You define the command once:
to square
repeat 4 [fd 100 rt 90]
end
Then you can use your new square command as many times as you want, just by typing its name.
How to Create a Simple Procedure
The structure of a procedure is simple. You can open the Logo editor (often by clicking the Edall button) to define your new commands.
- You start the definition with the keyword to, followed by the name for your new command.
- You list the commands you want the procedure to execute.
- You finish the definition with the keyword end.
to square
repeat 4 [fd 100 rt 90]
end
Making Procedures Flexible with Inputs (Arguments)
We learned that variables let us easily change a single value. Procedures let us package a whole set of actions. The real power comes when we combine them, creating procedures that use variables to become flexible and reusable.
The magic happens when you give your procedures inputs (also called arguments). An input is a way to pass information, like a size or a count, into your procedure, making it adaptable. You do this by defining a variable name right after the procedure name.
Let’s modify our square recipe to accept a size as an input.
to square :n
repeat 4 [fd :n rt 90]
end
Here, :n acts as a placeholder for whatever value we provide when we call the procedure. Now, we can draw squares of any size with a single, flexible command:
- square 50 draws a small square (where :n becomes 50).
- square 100 draws a larger square (where :n becomes 100).
Building Blocks: Combining Procedures
Once you’ve defined a procedure, you can use it inside another procedure. This is like using a recipe for “frosting” inside your recipe for “cake.” It allows you to combine simple shapes into more complex patterns, using your own procedures as building blocks.
For example, you can create a flower procedure that calls your square procedure multiple times to create a floral pattern.
to flower
repeat 6 [rt 60 square 100]
end
When you run flower, the turtle will draw six squares, each rotated 60 degrees from the last, creating a beautiful, complex image from a very simple building block.
Now that the turtle can remember things and learn new reusable tricks, the final step is to give it a mind of its own.