Comp 210 Lab 10: Accumulators, Homework hints

Accumulators, Homework hints


A Funny Function

Consider the function f : positive -> positive,
f(n) = 1 if n=1
n/2 if n is even
3n+1 if n is odd
While it may look like a pretty mundane function, try iterating it (repeating it over and over, using the previous result), and seeing how long it takes to reach 1 (if ever). This is known as Colatz's function, and we've seen it before in threes:

; threes : N[>=1] -> N[>=1]
(define (threes n)
   (cond [(= n 1)  1]
         [else     (cond [(even? n) (threes (/ n 2))]
                         [else      (threes (+ 1 (* n 3)))])]))
Note that it is generative recursive.

An example: if we start with (say) 5, we find that:

So starting with an initial value of 5, iterating f leads to 1 in five steps. "Sure," you say, "that starting point of 5 happens to lead to 1 after a few steps, just lucky!" What if we start iterating from 3? From 17?

To do: Write a program stops? which takes a number n, and returns true if n, f(n), f(f(n)), ... ever reaches the number 1, i.e., if (threes n) stops. (What does your program do if this doesn't happen?) It should not call threes, but it will resemble it. (Hint: Add an accumulator to a copy of threes.)

Q: Why do we choose to stop at f(1)?

Q: Does threes stop for all inputs? (Don't feel bad if you can't answer this. No one else has yet.)

To do: Now, write a function time-til-stop, which instead of returning true, it returns the number of steps until 1 is reached. That is, (time-til-stop 5) = 5. Test your program on some large numbers, say 1001, 2349872349247990, and 2349872349247991.


To do: Recall the equational definition of foldl:

     (foldl f base (list x1 x2 ... xN)) = (f xN ... (f x2 (f x1 base))...)
Write foldl using structural recursion and an accumulator.

Homework hints

In lab, we will discuss some ideas about what states are for the Missionaries & Cannibals problem. The following are some generalities to consider:

  1. The first step is to think about is what pieces of information are important to know. For this problem, what do we need to know about the missionaries, cannibals, boat, and sides of the river?
  2. The second step is to choose how to represent that data.

Your M&C program needs to build up a list of moves to the result. That sounds sort of similar to our in-class example that built up a list of cities for a path in a graph.