World 4: Functions
Patterns with names
- Some move patterns come back again and again: a hop over a tree, a set of stairs.
- Give the pattern a name once. Then use the name.
Words for this world
| Word | Meaning |
|---|---|
| function | a named block of code you can use many times |
| parameter | a value you give to the function |
| call | run the function by its name |
Name a pattern
PROCEDURE Hop()
OUTPUT "up"
OUTPUT "right"
OUTPUT "down"
ENDPROCEDURE
CALL Hop()
CALL Hop()
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a function procedure Go(Direction, Steps) that outputs direction steps times. Then call it: CALL Go("right", 3), CALL Go("down", 2), CALL Go("left", 3).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Trees stand on the road. Write a procedure Hop() that jumps over one tree: up, right, right, down. Use it to reach home.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a procedure Visit(): step right, go up to the star, and come back down. Visit three times, then walk home.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a procedure Stairs(N): N times right then down. Call Stairs(3), then walk the last 2 squares right.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a function Opposite(Move) that returns the opposite move (right gives left, down gives up, …). Walk the path, dig, then walk the path backwards with Opposite, and take one more step left home.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Write a procedure Zig(): right, right, down. Call it in a loop to collect all 3 stars and reach home.
คลิก Run เพื่อดูผลลัพธ์ที่นี่