Functions and Commands


Using commands to compute a function

One way to compute a function is to give a sequence of commands to perform. Those commands should give a name to the answer. Just in front of the commands, write the name of the answer followed by a vertical bar. (The vertical bar is typically on a key just above the enter key, along with the backslash character.) For example,

  Define
    absolute(x) = y |
      Let y = x.
      If y < 0 then
        Relet y = -y.
      %If
  %Define
defines function absolute(x) by saying that the answer is the value of y after performing the given sequence of statements.

Here is a function that computes the larger of two numbers x and y.

  Define
    larger(x:Integer, y:Integer): Integer by

    larger(x,y) = z |
      Let z = x.
      If z < y then
        Relet z = y.
      %If
  %Define

The part of the function definition after the bar is called the function body. The part before the = sign is called the function heading.


Indentation

Notice the indentation in the example. You indent the commands beneath the equation line that ends on a bar.


Problems

  1. [solve] Using the statement approach, write a function smaller(x, y) that produces the smaller of two integers. Include Define ... %Define around it.

  2. [solve] Using the statement approach, write a function smallest(x, y, z) that produces the smallest of thre integers. Include Define ... %Define around it. (Hint. First guess that the answer is x. Then update your guess to y if y is smaller than the current guess. Then update your guess to z if z is smaller than the current guess.)


Summary

You can use a sequence of statements to compute the answer that a function produces. Just say before the statements which variable is the one that holds the answer, and follow it by a bar.


Review

An If-statement allows you to make a decision either to do one sequence of statements or another.


Review questions

  1. [solve] The following function sum(n) yields 1 + 2 + ... + n, the sum of the first n positive integers. For example, sum(3) = 1 + 2 + 3 = 6 and sum(5) = 1 + 2 + 3 + 4 + 5 = 15.

      case sum(n) = 1              when n == 1
      case sum(n) = sum(n-1) + n
    
    Do a step-by-step evaluation of sum(4).

  2. [solve] Using recursion and equations, write a definition of function sumOdds(n), which produces the sum of the odd integers that are less than or equal to n. Assume that n is an odd positive integer. For example, sumOdds(3) = 1 + 3 = 4, and sumOdds(7) = 1 + 3 + 5 + 7 = 16. Use recursion.

    (Hint. For n = 1, just say what the answer is. For n > 1, look for a smaller problem of the same kind that will help you, and use the same function to solve that smaller problem.)