[Haskell-beginners] read

Brent Yorgey byorgey at seas.upenn.edu
Wed Oct 27 11:21:18 EDT 2010


On Tue, Oct 26, 2010 at 11:36:35PM -0700, Russ Abbott wrote:
> Hi,
> 
> I'm having a problem with the read function. I thought it took a string and
> converted it into a value (if there is a conversion). But it doesn't seem to
> work for me on GHCi
> 
> Prelude> read "123"
> *** Exception: Prelude.read: no parse
> Prelude> read (show 123)
> *** Exception: Prelude.read: no parse

Since read has type

  read :: Read a => String -> a

read "123" has type

  read "123" :: Read a => a

that is, read "123" can have *any* type which is an instance of Read.
GHC cannot figure out which type you want just by looking at the
string.

Now, normally in this situation you would get an "ambiguous type"
error.  However, ghci also has sometype defaulting rules: normally
they make things easier/more intuitive, but in this particular case
they make things more confusing!  What is happening is that since ghci
doesn't know what type your expression should have, it defaults it to
type ().  Now when it tries to read "123" as a value of type () it
fails.

As someone else already pointed out, the solution is to give a type
annotation to let ghci know what type you are expecting.

  Prelude> read "123" :: Int
  123
  Prelude> read "123" :: Double
  123.0

Note, however, that when using read in a the larger context of a
program, it is usually unnecessary to provide a type annotation, since
the type can be inferred from the context.  For example,

  addStrings :: String -> String -> Int
  addStrings x y = read x + read y

-Brent


> 
> 
> There must be something trivial that I'm missing.
> 
> Thanks.
> 
> *-- Russ Abbott*

> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners



More information about the Beginners mailing list