[Haskell-beginners] Re: Type problems with IOArray

apfelmus apfelmus at quantentunnel.de
Fri Oct 24 12:25:23 EDT 2008


Xuan Luo wrote:
> I am having lots of trouble using polymorphic mutable IOArrays. Here
> is an example program:
> 
> import Data.Array.MArray
> import Data.Array.IO
> 
> foo x = do a <- newArray (0, 4) x
>            readArray a 2
> 
> main = foo 42 >>= print
> 
> So there is a function "foo" which makes an array of polymorphic type
> initialized with a value, then returns one of the elements of the
> array.

Note that there are no arrays with "polymorphic element type", it's
rather that your  foo  can be used to create an array with elements the
same type as  x . So, if  x  is an integer,  foo  creates an array with
integer elements etc.

> What the heck is this? I looked through a lot of stuff online and
> eventually found that this works:
> 
> {-# LANGUAGE ScopedTypeVariables #-}
> import Data.Array.MArray
> import Data.Array.IO
> 
> foo :: forall a. a -> IO a
> foo x = do a <- newArray (0, 4) x :: IO (IOArray Int a)
>            readArray a 2
> 
> main = foo 42 >>= print
> 
> So I had to add some weird "forall" stuff to my function signature and
> enable some language extension flag(?). This seems way too
> complicated.

The  forall  is not weird :). In fact, the type signature

  foo :: a -> IO a

should be seen as an abbreviation for

  foo :: forall a. a -> IO a

See also

  http://en.wikibooks.org/wiki/Haskell/Polymorphism


Here, the  forall a  introduces  a  as type variable so that  IOArray
Int a  refers to the same type  a . You need an extension for that
because for some odd reason, Haskell98 offers no way to do that; it will
likely be included in the next version of the Haskell language.


Regards,
apfelmus



More information about the Beginners mailing list