Fortunately, though, it is possible for a Maple user to define
new functions. This is one of the key things that makes Maple less
like a calculator and more like a programming language. It is also
what will make you less like a calculator user and more like a
programmer.
Let's begin with a simple example. Suppose that you'd like to have a
function called square that takes a number as a parameter and
returns its square as its result. Here's how to do that in Maple:
| square := x -> x*x; |
Now you can use the function square just as if it were built in.
Here's one example of its use; you should experiment with others.
| square(5); |
The definition of the square function may look funny to you. We are
using assignment to name the function square. The ->
symbol is what tells Maple that we are defining a function. To the
left of the arrow appears the function's parameter, and to the
right is the function's body.
When you use a user-defined function, Maple takes the parameter that
you provide (5 in the example above), substitutes it for the parameter
(x) throughout the body of the function (x*x), yielding an expression
(5*5), which it then evaluates as usual (producing 25 in the example
above).
Try writing a function called cube that takes one parameter and
returns its cube. Try it out to make sure it works. When you're
done, congratulations--you've just written a program.
Now let's return to our original problem. We'd like to have a
function called compound that will calculate compound interest.
So let's define one:
| compound := (P,R,n) -> P*(1+R)^n; |
There's one extra complication here. The function compound
takes three parameters instead of one, which requires listing all three
of the parameters as shown. Now to calculate the consequences of
investing $100 at 5% interest for 50 years, we need only do:
| compound(100, .05, 50); |
See if you can use the compound function to answer the following
questions involving compound interest.
- If you invest $1000 at 6% interest right now, how much will it
be worth in 40 years?
- What if you invest it at 12% for 20 years?
Joseph L. Zachary
Hamlet Project
Department of Computer Science
University of Utah