35 — Todo list: adding, dropping, listing
Every program so far asked once and stopped. A program people actually use keeps taking commands until it is told to stop. One list and one loop that keeps going is all it takes.
Steps
A loop with no count is
repeat forever. Getting out needsbreak:
run it →repeat forever ask command say quit to stop if command equals quit break end show got it end show that is everythingWithout the
breakthe program never ends.Adding is one line into a list:
run it →set jobs to an empty list append buy milk to jobs append read a book to jobs show how many jobs show jobs joined by comma2, thenbuy milk, read a book.Dropping something that is not there stops the program, so ask first. Put what you are looking for in a name — something written as several words cannot go straight into a condition:
run it →set jobs to an empty list append buy milk to jobs set wanted to buy milk if jobs contains wanted remove wanted from jobs else show there is no such job end show how many jobsYou get
0.Four commands means three
else ifs. The lastelseis the way out:
run it →set command to drop if command equals add show adding else if command equals drop show dropping else if command equals list show showing else show stopping endThe whole thing:
run it →set jobs to an empty list repeat forever ask command one of add, drop, list, quit if command equals add ask job what needs doing append job to jobs else if command equals drop ask job what is done if jobs contains job remove job from jobs else show there is no such job end else if command equals list show how many jobs show jobs joined by comma else break end end show that is everything
Try it yourself
Make list show one job per line — inside for each job in jobs with place,
showing the place and the job gives you a numbered list. Closing the program
loses everything; keeping it in a file is what guide 37 is for.
What you learned
repeat foreverruns until it meetsbreak. Always leave a way out.- Several commands means
else ifin a row, with the lastelseas the exit. - Asking whether something is there before dropping it is what keeps the program running.
- One list is enough to be a program — it just disappears when you close it.