Performing Hand Simulations with Functions


Skipping to the answer

In the previous chapter, we defined jump(n) as follows.

  case jump(n) = 3*n + 1    when isOdd(n)
  case jump(n) = n `div` 2
Look again at the hand simulation of jump(7).
  jump(7) 
    = 3*7 + 1             (since isOdd(7) is true)
    = 21 + 1
    = 22
Notice that we do not bother with details of how the value of isOdd(7) is obtained, since we know what it does. Now suppose that isOdd is not something that is already available, but you define it.
  isOdd(n) = n `div` 2 == 1
Does the hand simulation need to change to show the details of how isOdd(7) is found? Surprisingly, the answer is no. You still know what isOdd does for you. So use that knowledge.

As a general rule, after you make each function definition, you try to understand what that function does for you. When doing a hand simulation, you use that knowledge for all functions except the one that you are testing. Just jump to the answer that you know the function should produce.


Problems

  1. [solve] Suppose that you have the following function definitions,

      case absolute(x) = x    when x >= 0
      case absolute(x) = -x
    
      absdiff(x,y) = absolute(x - y)
    
      f(u,v,w) = absdiff(u,v) + absdiff(v,w)
    
    You know that absolute(x) computes |x| and absdiff(x,y) computes |x - y|. Do an evaluation of f(3,5,9). Use the rule that you skip directly to the answer for functions that are not the one you are testing.


Summary

When doing hand simulations, you normally jump directly to the answer when you are using functions that are not the one you are testing, provided you know what that answer is supposed to be. That is, you presume functions that you wrote and tested earlier work correctly.


Review

A common way to solve problems is to break them down into cases, where you have a different way to solve each case. You can do that by deciding among equations to use. The conditions themselves can involve functions that you have defined.