Programs with Structure

Procedures that take values and give one back

Read a procedure that is handed values to work on, and work out what a call to it gives.

A procedure that always does exactly the same thing is useful but narrow. What makes procedures worth the trouble is that a procedure can be handed values to work on. Names written in the brackets of the heading are placeholders, and a call fills them in, in the order they were written. Inside the block those names behave like any other variable, holding whatever this particular call handed over. And a procedure can hand something back: the word return names a value, stops the block there and then, and gives that value to whoever made the call.

A call that gives something back is a value

Once a procedure returns, a call to it is not an instruction any more — it is a value, and it can go anywhere a value can go. You can print it, store it in a variable, do arithmetic with it, or hand it straight to another call as one of that call's values. Working these out is always done from the inside outwards: whatever is deepest inside the brackets has to become a value before anything wrapped around it can even begin. That single habit settles almost every question about calls, however tangled they look.

Worked example

A procedure named scale takes one number and gives back that number multiplied by 5, take away 1. What does a call to it with 4 give?

  1. The heading's placeholder stands for the value handed over, so wherever the block says that name, read 4 instead.

    Doing this substitution on paper is the whole trick. Everything after it is ordinary arithmetic with no procedures in it at all.

Try it together

Now work some calls out together. A procedure named boost takes one number and gives back that number multiplied by 4, plus 1.

Substitute first, then do the arithmetic.

    1.What does boost(2) give?

    Have a go

    Have a go on your own. A procedure named drop takes one number and gives back that number take away 6. What does drop(15) give?

    Ready to practise?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet