
Functions, their arguments, and parameters
You can dene your own functions in a program, and data can be passed to a function using parameters.
Functions can return a value (using the RETURN statement) or not. When a program is executed from Home
view, the program will return the value returned by the last statement that was executed.
Furthermore, functions can be dened in a program and exported for use by other programs, in much the
same way that variables can be dened and used elsewhere.
In this section, we will create a small set of programs, each illustrating some aspect of programming in the HP
Prime. Each program will be used as a building block for a custom app.
Program ROLLDIE
We’ll rst create a program called ROLLDIE. It simulates the rolling of a single die, returning a random integer
between 1 and whatever number is passed into the function.
In the Program Catalog create a new program named ROLLDIE. (For help, see Creating a new program
on page 554.) Then enter the code in the Program Editor.
EXPORT ROLLDIE(N)
BEGIN
RETURN 1+RANDINT(N-1);
END;
The rst line is the heading of the function. Execution of the RETURN statement causes a random integer
from 1 to N to be calculated and returned as the result of the function. Note that the RETURN command
causes the execution of the function to terminate. Thus any statements between the RETURN statement and
END are ignored.
In Home view (in fact, anywhere in the calculator where a number can be used), you can enter ROLLDIE(6)
and a random integer between 1 and 6 inclusive will be returned.
Program ROLLMANY
Because of the EXPORT command in ROLLDIE, another program could use the ROLLDIE function and generate
n rolls of a die with any number of sides. In the following program, the ROLLDIE function is used to generate
n rolls of two dice, each with the number of sides given by the local variable sides. The results are stored in
list L2, so that L2(1) shows the number of times the dies came up with a combined total of 1, L2(2) shows the
number of times the dies came up with a combined total of 2, etc. L2(1) should be 0 (since the sum of the
numbers on 2 dice must be at least 2).
Here we use the Store operator (▶) in place of :=. Press to retrieve this operator. The syntax
is Var ▶ Value; that is, the value on the right is stored in the variable on the left.
EXPORT ROLLMANY(n,sides)
BEGIN
LOCAL k,roll;
// initialize list of frequencies
MAKELIST(0,X,1,2*sides,1) ▶ L2;
The HP Prime programming language 569
Komentarze do niniejszej Instrukcji