collatz.ss
#lang scribble/lp

Consider a function that, starting from @scheme[(collatz n)],
recurs with 

@chunk[<even> 
       (collatz (/ n 2))]

if @scheme[n] is even and recurs with

@chunk[<odd> 
       (collatz (+ (* 3 n) 1))]

if @scheme[n] is odd.

We can package that up into the @scheme[collatz] function:

@chunk[<collatz> 
       (define (collatz n) 
         (unless (= n 1) 
           (if (even? n) 
               <even> 
               <odd>)))] 

The @italic{Collatz conjecture} is true if this function
terminates for every input. 

Thanks to the flexibility of literate programming, we can
package up the code to compute orbits of Collatz numbers too:

@chunk[<collatz-sequence> 
       (define (collatz n) 
         (cond 
           [(= n 1) 
            '(1)] 
           [(even? n) 
            (cons n <even>)] 
           [(odd? n)
            (cons n <odd>)]))]

Finally, we put the whole thing together, after
establishing different scopes for the two functions.

@chunk[<*>
       (require scheme/local)
       (local [<collatz-sequence>]
         (collatz 18))
       (local [<collatz>]
         (collatz 18))]