Loops that Accumulate Results


Loops that Accumulate Answers

Some loops run through a sequence of values accumulating some number as they go. The following loop, for example, makes r = n! (assuming that we already know what n is in this context). It starts r at 1. Then it goes through the numbers 2, 3, ..., n, multiplying r by each of them.

  Let r = 1.
  Let k = 2.
  While k <= n do
    Relet r = r * k.
    Relet k = k + 1.
  %While
Let's put that loop into a function that computes factorials. Now the loop is put into a context where n is known (because somebody else told the function a value of n to use).
  Define
    factorial(n: Integer): Integer by

    factorial(n) = r |
      Let r = 1.
      Let k = 2.
      While k <= n do
        Relet r = r * k.
        Relet k = k + 1.
      %While
  %Define


Case study: Count the vowels in a string

Suppose that we already have a function isVowel(c) that produces true when character c is a vowel. Let's write a function, using a loop, that counts the number of vowels in a string s. The idea is to keep a count of the number of vowels seen. Initially, it is 0. Then look at each character in the string. If it is a vowel, add one to the count.

  Define
    numVowels(s: String) : Integer by
 
    numVowels(s) = count |
      Let slen = length(s).
      Let count = 0.
      Let k = 1.
      While k <= slen do
        If isVowel(s_k) then
          Relet count = count + 1.
        %If
        Relet k = k + 1.
      %While
  %Define


Problems

  1. [solve] Suppose that the factorial function is defined as follows.

      Define
        factorial(n: Integer): Integer by
    
        factorial(n) = r |
          Let r = 1.
          Let k = 2.
          While k <= n do
            Relet r = r * k.
            Relet k = k + 1.
          %While
      %Define
    
    Do a careful hand simulation of factorial(4).

  2. [solve] Using a loop to accumulate the result, define function power(x,n), which returns xn. Assume that x is a real number and n is a positive integer. Write the function with Define ... %Define around it.


Summary

Some loops go through a sequence of values accumulating an answer as they go.