[Haskell-beginners] permuting a list
Jan Snajder
jan.snajder at fer.hr
Thu Feb 12 04:20:32 EST 2009
Hi!
I'm trying to write a list permutation function, and there is in fact a
nice explanation of how to do it here:
http://sneakymustard.com/2008/12/23/shuffling-in-haskell
But for the start I wanted to keep things simple and avoid monad
transformers (since I'm not into this yet). Instead, I'd like to write a
function of type:
> permute :: [a] -> IO [a]
and so this is what I did:
> permute xs = do
> let n = length xs - 1
> arr0 <- newListArray (0, n) xs
> arr <- foldM swap arr0 [n..1]
> getElems arr
> where swap arr n = do
> x <- readArray arr n
> r <- randomRIO (0, n)
> y <- readArray arr r
> writeArray arr n y
> writeArray arr r x
> return arr
Unfortunately, what I get is:
> permute :: (MArray a1 a IO) => [a] -> IO [a]
and so when I try to apply this function:
> permute [1,2,3]
this is what I get:
<interactive>:1:0:
No instance for (MArray a1 t IO)
arising from a use of `permute' at <interactive>:1:0-14
Possible fix: add an instance declaration for (MArray a1 t IO)
In the expression: permute [1, 2, 3]
In the definition of `it': it = permute [1, 2, 3]
How can I fix this?
Thanx,
jan
More information about the Beginners
mailing list