Python · Exercise 5 of 5 Previous
Advanced
Describe commands with match
The starter defines four dataclasses: Move(dx, dy), Say(text), Quit() and Unknown(text). Write describe(cmd) using match with class patterns that returns "move by 3, 4" for Move(3, 4), "say: hi" for Say("hi"), "bye" for Quit() and "unknown: xyz" for Unknown("xyz").
Also make Move(0, 0) return "stay": give it its own case and put that case before the general Move case, because the first matching case wins. Anything that is not one of the four classes should end in assert_never(cmd) in the last case.
What Check tests
Move(3, 4)givesmove by 3, 4Move(0, 0)givesstay- Only the exact origin is
stay Say,QuitandUnknownare described- The function uses
matchandcase - Anything else raises
AssertionErrorthroughassert_never - The program prints the first description
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.