Next: Types Answer 1, Previous: List Answer 13, Up: Answers to Exercises

#### 3.7.32 List Tutorial Exercise 14

We want to use `H V U` to nest a function which adds a random step to an ‘`(x,y)`’ coordinate. The function is a bit long, but otherwise the problem is quite straightforward.

         2:  [0, 0]     1:  [ [    0,       0    ]
         1:  50               [  0.4288, -0.1695 ]
             .                [ -0.4787, -0.9027 ]
                              ...

             [0,0] 50       H V U ' <# + [random(2.0)-1, random(2.0)-1]> <RET>

Just as the text recommended, we used ‘`< >`’ nameless function notation to keep the two `random` calls from being evaluated before nesting even begins.

We now have a vector of ‘`[x, y]`’ sub-vectors, which by Calc's rules acts like a matrix. We can transpose this matrix and unpack to get a pair of vectors, ‘`x`’ and ‘`y`’, suitable for graphing.

         2:  [ 0, 0.4288, -0.4787, ... ]
         1:  [ 0, -0.1696, -0.9027, ... ]
             .

             v t  v u  g f

Incidentally, because the ‘`x`’ and ‘`y`’ are completely independent in this case, we could have done two separate commands to create our ‘`x`’ and ‘`y`’ vectors of numbers directly.

To make a random walk of unit steps, we note that `sincos` of a random direction exactly gives us an ‘`[x, y]`’ step of unit length; in fact, the new nesting function is even briefer, though we might want to lower the precision a bit for it.

         2:  [0, 0]     1:  [ [    0,      0    ]
         1:  50               [  0.1318, 0.9912 ]
             .                [ -0.5965, 0.3061 ]
                              ...

             [0,0] 50   m d  p 6 <RET>   H V U ' <# + sincos(random(360.0))> <RET>

Another `v t v u g f` sequence will graph this new random walk.

An interesting twist on these random walk functions would be to use complex numbers instead of 2-vectors to represent points on the plane. In the first example, we'd use something like ‘`random + random*(0,1)`’, and in the second we could use polar complex numbers with random phase angles. (This exercise was first suggested in this form by Randal Schwartz.)