Bundling instructions

Parts of sequences

Sequences often contain parts that come up multiple times and in very similar ways. Can you think of such a part?

  • Having breakfast

True that! A breakfast routine may well come up every day, while the other parts of sequences may vary too much.

Procedures

Programs, too, contain parts that come up again and again. For example, what might happen when we cut text?

OK computer:
  • remember text
    delete text

Perfect! Cutting text involves remembering and deleting a text snippet while leaving the cursor where it is.

Defining procedures

In order to reuse a procedure, we need to tell the computer what the procedure looks like.

OK computer:
remember as cutting:
 remember selected text
 delete selected text

As soon as we have defined a procedure, we can reuse it anywhere in the program.

Pre-defined procedures

Pretty much anything we can tell the computer to do, including cutting, is actually a pre-defined procedure.

OK computer:
create a list of my_friends
add "Phoebe", "Chandler", and "Rachel" to my_friends
sort my_friends in alphabetical order
display my_friends

//Output Below

Chandler, Phoebe, Rachel

There! How would the computer know how to create or display a list let alone sort it without pre-defined procedures?

Taking input

When we pass information, or input, to procedures, they become more flexible.

OK computer:
remember as greeting somebody:
 display "Hey ", somebody, and "!"

Yass! By passing a name to the procedure, we can make it more flexible.

Giving output

Parts of sequences aren't limited to tasks, though. They can also produce information, or output.

OK computer:
remember as converting miles to kilometers:
 multiply miles by 1.60934
return the result

Great! While procedures perform tasks, so-called functions produce, or returns, output.

Using functions

Then, how might we get the computer to display 5 miles in kilometers?

OK computer: convert 5 miles to kilometers
remember the result as kilometers
display kilometers

Good stuff! Because functions return something, the computer needs to remember the result in order to display it.