"Ambigous type variable" error when defining custom "read" function
Posted
by Tener
on Stack Overflow
See other posts from Stack Overflow
or by Tener
Published on 2010-03-24T22:54:23Z
Indexed on
2010/03/25
3:23 UTC
Read the original article
Hit count: 387
While trying to compile the following code, which is enhanced version of read build on readMay from Safe package.
readI :: (Typeable a, Read a) => String -> a
readI str = case readMay str of
Just x -> x
Nothing -> error ("Prelude.read failed, expected type: " ++
(show (typeOf > (undefined :: a))) ++
"String was: " ++ str)
I get an error from GHC:
WavefrontSimple.hs:54:81:
Ambiguous type variable `a' in the constraint:
`Typeable a'
arising from a use of `typeOf' at src/WavefrontSimple.hs:54:81-103
Probable fix: add a type signature that fixes these type variable(s)`
I don't understand why. What should be fixed to get what I meant?
EDIT: Ok, so the solution to use ScopedTypeVariables
and forall a
in type signature works. But why the following produces very similar error to the one above? The compiler should infer the right type since there is asTypeOf :: a -> a -> a
used.
readI :: (Typeable a, Read a) => String -> a
readI str = let xx = undefined in
case readMay str of
Just x -> x `asTypeOf` xx
Nothing -> error ("Prelude.read failed, expected type: "
++ (show (typeOf xx)) ++
"String was: " ++ str)
© Stack Overflow or respective owner