[Haskell-beginners] Question about List Type Constraint and Null

Daniel Fischer daniel.is.fischer at googlemail.com
Sat Jan 22 20:22:47 CET 2011


On Saturday 22 January 2011 19:45:40, Jürgen Doser wrote:
> El sáb, 22-01-2011 a las 11:06 -0600, aditya siram escribió:
> > Ok I've figured out why I can't compile it. But now I'm more confused
> > than ever. The problem was that I have a -XNoMonomorphismRestriction
> > flag on Ghci. Removing this allowed me to compile.
>
> This is indeed a bit tricky, it seems. res has a type-class polymorphic
> type Read a => ... (the ... is complicated by the fact that you have
> given a strange signature to test, see below)
>
> With the monomorphism restriction on, ghc takes the type-signature for
> test, inferes a type for res in the line Just $ fst $ head res, and uses
> this type for the null res test. Interestingly, it doesn't infer a
> monomorphic type for res, but insists that the instantiation for the
> type-class parameter is the same in both occurences.
>
> With no monomorphism restriction, ghc doesn't do this inference, because
> the type for res in null res may be different to the type of res in Just
> $ fst $ head res. (i.e., the instantion for the type-class parameter may
> be different)

You can however make ghc consider res a monomorphic value even with the MR 
turned off by
a) turning on MonoLocalBinds
b) turning on ScopedTypeVariables, bringing a into scope (via forall a) and 
giving res a type signature involving that a

or you can avoid all these problems by using the nicer code

test s = case reads s of
            [] -> Nothing
            ((x,_):_) -> Just x

>
> Finally, are you sure that the given type signature is what you want?
> Don't you want
>
> test ::  Read a => String -> Maybe a
>
>
> 	Jürgen



More information about the Beginners mailing list