SICP Exercise 3.19 detect cycle in constant space


Exercise 3.19.  Redo exercise 3.18 using an algorithm that takes only a constant amount of space. (This requires a very clever idea.)

SOLUTION

I use the definition of an iterative process from section 1.2.1. here.

Scheme will execute an iterative process in constant space, even if the iterative process is described by a recursive procedure. An implementation with this property is called tail-recursive. With a tail-recursive implementation, iteration can be expressed using the ordinary procedure call mechanism. In general, an iterative process is one whose state can be summarized by a fixed number of state variables, together with a fixed rule that describes how the state variables should be updated as the process moves from state to state and an (optional) end test that specifies conditions under which the process should terminate. The program variables provide a complete description of the state of the process at any point. If we stopped the computation between steps, all we would need to do to resume the computation is to supply the interpreter with the values of the program variables. An interpreter need keep track of only these variables in order to execute the process.

See in the code below that there are no deferred evaluations that are typical of a recursive process. Deferred evaluations result in continuously increasing space usage since the interpreter needs to keep track of operations to be performed later on.

Additionally, I am doing away with the 'visited-pairs' list altogether and using the hare-and-tortoise algorithm in which one pointer advances one step at a time and the other pointer advances two steps at a time.

The code is here:


Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions