[Haskell-beginners] Type declaration

Brandon Allbery allbery.b at gmail.com
Sun Apr 12 16:55:05 UTC 2015


On Sun, Apr 12, 2015 at 12:41 PM, Christian Sperandio <
christian.sperandio at gmail.com> wrote:

> I’m currently playing with the mutable array to implement an heap sort
> sort (from The Art of Computer Programming) and I’m puzzled with an error.
>
> When I code:
>
> toHeap :: Ord a => [a] -> IO [a]
> toHeap [] = return []
> toHeap [x] = return [x]
> toHeap xs = do
>   arr <- newListArray (1, length xs) xs :: IO (IOArray Int a)
>   getElems arr
>

Note that the "a" in the signature "IO (IOArray Int a)" is *not* the same
as the one in the signature of toHeap; the scope of that type variable is
the signature itself, not the following equation(s). You have in effect
done the opposite of what you intended --- instead of asserting it is the
same, you asserted that it is a *different* one, by handing the compiler an
unexpected `a` which must be assumed to represent a distinct type.

If you need to extend the scope of a type variable like this, you need the
ScopedTypeVariables extension, and to declare the type variable as having
extended scope with an explicit `forall`:

{-# LANGUAGE ScopedTypeVariables #-}

toHeap :: forall a. Ord a => [a] -> IO [a]
toHeap [] = return []
toHeap [x] = return [x]
toHeap xs = do
  arr <- newListArray (1, length xs) xs :: IO (IOArray Int a)
  getElems arr

-- 
brandon s allbery kf8nh                               sine nomine associates
allbery.b at gmail.com                                  ballbery at sinenomine.net
unix, openafs, kerberos, infrastructure, xmonad        http://sinenomine.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150412/ff6a145f/attachment.html>


More information about the Beginners mailing list