Simon Richard Clarkstone <s.r.clarkst...@durham.ac.uk> writes:
> rincewind wrote:
> > I'm struggling with monads, and my brain hurts...
> > How somebody show me how I can implement an in-place modification of
> > an Array with monads? Say, I have to write the swap function (I'm
> > not sure about the correctness of this function declaration, but you
> > should get the idea):
> > swap ar i j :: Array a -> Ix -> Ix
> I have cross-posted this to comp.lang.haskell, which is for just this
> sort of thing.
> Try looking at Control.Monad.ST, Data.Array.ST, and Data.Array.MArray.
> The typeclasses used there are complicated, but your signature seems
> wrong to me.
The type "Array" is immutable; you will not in-place modify its elements.
The mutable arrays are IOArray and STArray; they require the IO monad
and the ST monad, respectively. In the ST case, as noted, the
relevant libraries are Control.Monad.ST and Data.Array.ST.
(Data.Array.MArray describes the generalization that unifies IOArray
and STArray. Therefore it will look abstract.)
In the ST case the correct type for swap should be:
swap :: (Ix i) => STArray s i e -> i -> i -> ST s ()
To swap, you read and write array elements. These are the functions
to use --- I show their types specialized to STArray (they have more
abstract types in Data.Array.MArray):
readArray :: (Ix i) => STArray s i e -> i -> ST s e
writeArray :: (Ix i) => STArray s i e -> i -> e -> ST s ()
Perhaps you are more interested in the IO monad at the moment. In the
IO case the types become:
swap :: (Ix i) => IOArray i e -> i -> i -> IO ()
readArray :: (Ix i) => IOArray i e -> i -> IO e
writeArray :: (Ix i) => IOArray i e -> i -> e -> IO ()
I'm wondering whether I should stop now and let you finish, now that
the objective and the tools are more concrete. But what the heck, if
you have problem even with monads...
swap ar i j = do x <- readArray ar i
y <- readArray ar j
writeArray arr i y
writeArray arr j x
I hope with the concrete types I've given, you can see what's going
on. (I practice Type-Oriented Programming.)