Sanity Checking Functions


A few things to check for

When you write an algorithm, you never just guess. Work it out carefully, and check that it works. Obviously, that requires a lot of detailed thought. Unfortunately, until you have a great deal of experience, you can find yourself lost in the details. But there are some checks that are easy to make, just to ensure that you have not made a silly blunder.

  1. Does a function make use of its argument(s)? If there is an argument called x, and you never even mention x while computing the answer, something is wrong. (When you define a function by cases, sometimes some of the cases only use some of the arguments. But every argument should be used in at least one case.)

  2. Does a function make use of variables that do not exist? If so, something is wrong. For example, if your function makes use of something called x, but x is not an argument and is not defined using Let, then there is a problem.

  3. If a function works by using commands, has it defined all variables that are required by the result? For example, suppose that you see a function definition

      Define
        f(x) = y |
          ...
      %Define
    
    and in the ... part you fail to say what y is. Something is wrong.

  4. Make sure that you have not used the same name for two different things. In particular, be sure that you have not created a variable whose name is the same as the name of an argument. You should never see something like this.

      Define
        f(x) = y |
          Let x = ...
          ...
      %Define
    


Problems

  1. [solve] What is wrong with the following function definition?

      Define
        hop(x,y) = w |
          Let x = 1.0.
          Let y = 2.0.
          Let answer = x + y + 1.
      %Define
    

  2. [solve] What is wrong with the following function definition?

      Define
        f(w) = q |
          Let q = x + y.
      %Define
    


Summary

It is worth the time to do a quick check to see that a function definition passes a few sanity checks. If it doesn't, it needs to be fixed.


Review

You can change the value of a variable using Relet.

In a given context, a given variable always has to have the same type.

It is a good idea to do a careful hand simulation, crossing out the old value of a variable when its value is changed.