Tail recursion (87)

64 Name: #!/usr/bin/anonymous : 2006-03-13 07:21 ID:Heaven

>How would that be done in practice, then? I have no idea what "you must explicitly sequence their manipulations using monads" means.

First, two primitive operations on mutable arrays are provided.

readArray :: STArray s i e -> i -> ST e
writeArray :: STArray s i e -> i -> e -> ST ()

Here, STArray s i e is something like pointer to array, i is index type of array (usually integer), e is rype of array element, and ST foo is an action whose result is of type foo. For example,

writeArray arr 4 'c'

is an action that, when performed, writes 'c' to the 4th element of the array arr.

Next, you can sequencially combine these actions, producing another action. For example,

writeArray arr 4 'c' >> writeArray arr 45 'd'

is an action that, when performed, writes 'c' to the 4th element and then writes 'd' to the 5th element of the array arr. Likewise, the following is the function that produce an action that swaps the ith and jth element of a specified array.

swap arr i j = 
readArray arr i >>= \x ->
readArray arr j >>= \y ->
writeArray arr i y >>
writeArray arr j x

Actions that can be combined like the above are called monads.

This thread has been closed. You cannot post in this thread any longer.