[Haskell-beginners] Re: permuting a list

Heinrich Apfelmus apfelmus at quantentunnel.de
Fri Feb 13 05:25:04 EST 2009


Jan Snajder wrote:
> Brent Yorgey wrote:
> 
>> The problem seems to be that
>> Haskell has no way to know what sort of array you want to use.  I was
>> able to get the code to work, but it's sort of sneaky:
>>
>>> {-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}
>>>
>>> import Data.Array.MArray
>>> import Data.Array.IO
>>> import Control.Monad
>>> import System.Random
>>> permute :: forall a. (MArray IOArray a IO) => [a] -> IO [a]
>>> permute xs = do
>>>   let n = length xs - 1
>>>   arr0 <- (newListArray (0, n) xs :: IO (IOArray Int a))
>>>   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

The type class constraint is not needed because IOArray can hold any
element type anyway. (It's unboxed arrays that only work for certain
element types). Thus, you can write  FlexibleConstraints  extension and
simply write

  permute :: forall a. [a] -> IO [a]

instead.

Also, I think that specifying the type of  arr0  as

  (arr0 :: IOArray Int a) <- newListArray (0, n) xs

should work as well.


-- 
http://apfelmus.nfshost.com



More information about the Beginners mailing list