[Haskell-cafe] REALLY simple STRef examples

Udo Stenzel u.stenzel at web.de
Thu Jul 20 17:33:36 EDT 2006


Chad Scherrer wrote:
> But why should this...
> 
> >sumArrays [] = error "Can't apply sumArrays to an empty list"
> >sumArrays (x:xs) = runSTArray (result x)
> >    where
> >    result x = do x0 <- thaw x
> >                  mapM_ (x0 +=) xs
> >                  return x0
> 
> work differently than this...
> 
> >sumArrays' [] = error "Can't apply sumArrays to an empty list"
> >sumArrays' (x:xs) = runSTArray result'
> >    where
> >    result' = do x0 <- thaw x
> >                 mapM_ (x0 +=) xs
> >                 return x0
> 
> Are the types of (result x) and result' not exactly the same?

It's the monmorphism restriction, again.  Because result' doesn't look
like a function, a monomorphic type is inferred for it.  runST[U]Array
of course doesn't want a monomorphic type.  It's got nothing to do with
boxed vs. unboxed arrays (I think, I can't be bothered to test it right
now).

There are at least four ways out:

- make result' a function, either as in the first example above or by
  supplying a dummy () argument
- declare the correct polymorphic type for result'
- inline result'
- (GHC only) compile with -fno-monomorphism-restriction

Yes, it's a bit cumbersome.  Imperative code is supposed to be
cumbersome, after all.  :)


Udo.
-- 
They seem to have learned the habit of cowering before authority even
when not actually threatened.  How very nice for authority.  I decided
not to learn this particular lesson.
                -- Richard Stallman
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20060720/898554c2/attachment.bin


More information about the Haskell-Cafe mailing list