Hello world |
Maple programs
are called procedures, and so they are defined with the
keyword proc
. Here is a basic Maple procedure:
hello:=proc() print(`hello world`); end;
This procedure has no arguments: hence the empty
parentheses after the keyword proc
. After executing this
code to define the procedure, you invoke the procedure via
hello();
, and Maple should respond by printing the
string "hello world".
Unfortunately, the notation Maple uses to delimit strings has changed regularly with new releases. Issue the Maple commands ?string and ?symbol to find out how your version works. If you change the above procedure to
hello:=proc() print("hello world"); end;
what difference does it make?
The procedure could be made a little more interesting as follows.
greeting:=proc() local name; print(`What is your name?`); name := readline( terminal ); print(`Hello `||name); end;
The second line of this procedure declares
"name
" to be a variable whose value is local to the
procedure. The third line prints a question on the screen, and
the fourth line takes the response from the user and stores it
in the variable "name
". The fifth line of the
procedure then prints a personalized message. (The double
vertical bars concatenate strings or names.) Try it! After
typing in the procedure, call it via greeting();
.
Here is a simple procedure that takes one argument:
half:=proc(n) n/2; end;
The command half(2000);
then produces the
output 1000
. Here is a variant of the procedure that
responds in words.
verbalhalf:=proc(n) printf("Half of %a is %.1f.", n, n/2); end;
Now verbalhalf(2001);
returns the response "Half of
2001 is 1000.5.
" Here the printf
command begins with a
formatting string with two placeholders. The %a
says to
insert the first variable in Maple syntax, and the %.1f
says to insert the second variable formatted as a
floating-point number with one digit after the decimal point.
This new procedure runs into trouble if you try to call it with
an argument that is not a number. For example,
verbalhalf(Texas);
will produce a cryptic error message.
A more informative error message results if you modify the
procedure to make it check the type of its argument:
betterhalf:=proc(n::numeric) printf("Half of %a is %.1f.", n, n/2); end;
Here proc(n::numeric)
indicates that the
argument n should be a number (an integer, a fraction, or a
floating-point number). If the procedure is called with an
argument that is, for example, a string rather than a number,
then an error message will indicate this. For
example,
betterhalf("a rude awakening");
produces the following error
message:
Error, invalid input: betterhalf expects its 1st argument, n, to be of type numeric, but received a rude awakening
Hello world |