[Haskell-beginners] permuting a list
Alexander Dunlap
alexander.dunlap at gmail.com
Thu Feb 12 10:00:34 EST 2009
On Thu, Feb 12, 2009 at 1:20 AM, Jan Snajder <jan.snajder at fer.hr> wrote:
> 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
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
The simplest way to do this is to use base v4, which I believe
contains a "permutations" function in Data.List.
Alex
More information about the Beginners
mailing list