Next: Lessons
Up: Programming With Functions
Previous: Function Specifications

Functions as Black Boxes

The information that I just gave you about my function is exactly the kind of information that should be apparent from reading the first few lines of the implementation of any well-written Fortran function. Here are the first few lines of my implementation:

C This function requires that "Q" be nonzero.  It returns the value of x that
C is the solution of the equation:
C
C                2
C         Px    x
C        e   = ---  
C               Q

      REAL FUNCTION SOLVE (P, Q)
      IMPLICIT NONE
      REAL P, Q

Notice that all the information is there---some of it is in the comments, and the rest is in the ``header'' of the function. You do not need to know anything else about the function in order to use it. In particular, you do not need to know anything about how the function is implemented. As long as you know what my function does, you don't need to know how it does it. And that's nice---it simplifies your life as a programmer.

This is a crucial idea that all programmers must eventually learn to appreciate. The five pieces of information outlined above are collectively called the function's interface, and they serve as a ``contract'' between the implementor and the user of a function. You can view the body of the function as a ``black box'' about which you need know nothing.

To help drive this point home, you are now going to write a program that uses SOLVE, but I'm not going to give you the implementation of SOLVE until you're done. Use Emacs to create a program called ``solve.f''. At the top of the program put the following ``implementation'' of SOLVE:

      REAL FUNCTION SOLVE (P, Q)
      IMPLICIT NONE
      REAL P, Q

      PRINT *, 'SOLVE called with', P, 'and', Q, 'as arguments'
      SOLVE = 0.0

      RETURN
      END

This ``implementation'' of SOLVE is called a stub. It has the same name, takes the same numbers and types of arguments, and returns the same type of result as the real SOLVE. But the stub doesn't do anything interesting. Why do we bother with it?

Click here for the answer

Your main program should read in values for P, and Q, use SOLVE to solve the equation, and then print out the result. Your first step is to get your program working with the stub above.

Once you have succeeded in doing that, go to your Emacs window, delete the stub, and click below. I'll put the correct definition of SOLVE into your Emacs buffer.

Click here to insert SOLVE into your Emacs buffer

You program should compile and run properly with no further modifications. The only difference is that now it should give the right answers.


Next: Lessons
Up: Programming With Functions
Previous: Function Specifications

Hamlet Project
hamlet@cs.utah.edu