[Haskell-cafe] Usage of Read Class

Ariel J. Birnbaum valgarv at gmx.net
Sun Mar 30 17:51:54 EDT 2008


> >  <interactive>:1:1:
> >     Ambiguous type variable `a' in the constraint:
> >       `Read a' arising from a use of `read' at <interactive>:1:1-4
> >     Probable fix: add a type signature that fixes these type variable(s)
>
> What the error message says is, it doesn't know which type to read to.
> read has the type Read a => String -> a, and unless you tell it what
> 'a' is going to be, how would it know? If you say '(read.show) x ::
> Color' it should work just fine.

Just to sharpen the point: read cannot know from the string it processes which 
type to deliver.

For example, try the following at the ghci prompt:

read "3"          -> Yields the same error as above
read "3" + 3      -> 6
read "3" + 3.3    -> 6.3
read "3.3" + 3.3  -> 6.6
read "3.3" + 3    -> Error: no parse

What's happening is that the type of the expression is determined by the 
literal on the _right_side_ of the + sign, and not by the contents of the 
string on the left side.

The last example is a bit tricky. ghci sees 3 on the rhs, which can be of any 
type in the Num class (as opposed to 3.3, which has to be of a Fractional 
type). If unresolved, it will default to Integer (or Int?), and try to 
parse "3.3" as such -- which will of course fail.

-- 
Ariel J. Birnbaum


More information about the Haskell-Cafe mailing list