Telling a Job What to Work On
A job that takes a value and hands one back, so one job can do a whole family of things.
The divider from Unit 2 does the same thing every time. That is fine for a divider. Most jobs are not like that: you want the same work done to a different value each time.
So you give the job something to work on.
Handing a value in
Put a name in brackets after the job’s name. That name stands for whatever the caller hands over:
DEFINE greet(who)
SHOW "Hello, ", who
END
CALL greet("Sam")
CALL greet("Ada")
Hello, Sam Hello, Ada
One job, two results. Inside greet, the box who holds whatever came in with the call:
"Sam" the first time, "Ada" the second.
That box belongs to the job. It holds its value while the job runs and means nothing
outside, so a who anywhere else in your program is a different box that happens to share
a name.
Handing a value back
A job can also give an answer. RETURN hands a value to whoever called, and the job stops
there:
DEFINE double(n)
RETURN n * 2
END
LET x = double(5)
SHOW x
10
double(5) runs the job with n set to 5, and the RETURN sends 10 back. That answer
lands where you wrote the call, so LET x = double(5) puts 10 in x.
Notice the two shapes are different on purpose. CALL greet("Sam") does a job and expects
nothing back. You use double(5) for its answer, so it sits where a value belongs.
When it’s wrong, see why
- The job always does the same thing. You named a value in the brackets but used a different name inside the job. The name in the brackets is the one that holds what came in.
- You get nothing back. The job has no
RETURN, or the program reached theENDwithout passing one. A job with nothing to hand back is one youCALLinstead. - You called it without the value it needs.
CALL greet()leaveswhoholding nothing. A job that takes a value wants one every time you call it.
What you’ve learnt
- A job can take a value: the name in brackets holds whatever the caller hands over.
RETURNhands a value back, and the answer lands where you wrote the call.- A job you
CALLdoes something. A job you use for its answer goes where a value goes. - The names inside a job belong to the job.
What’s next
You now have every idea that goes into a program: instructions, order, output, memory, input, arithmetic, decisions, loops, lists and named jobs. One thing remains, and it is the most useful of all. In Unit 4 we find out what to do when a program does the wrong thing.