[Haskell-beginners] The type class Read
Francesco Ariis
fa-ml at ariis.it
Fri Jul 13 07:30:37 UTC 2018
On Fri, Jul 13, 2018 at 09:06:51AM +0200, mrx wrote:
> That makes sense to me based on the type, sure. So read is some form of
> casting then?
Yep, but just from `String` and nothing else.
>
> Does this answers your question?
>
>
> Maybe, but I still don't see what I'd use it for. Is it used to for example
> read the contents of a file whose file name is provided as that string?
No, you would use `readFile` for that:
readFile :: FilePath -> IO String
-- Filepath is a type synonym for `String`
You would use `read` to convert simple user input (which is usually
collected as String) into, say, Integers
getLine :: IO String
-- this could need read
And in general, `Read` is supposed to be compatible with `Show`, so
if you used `show` for any reason (some form of cheap serialisation,
etc.), `read` should work back the type:
λ> show [1..10]
"[1,2,3,4,5,6,7,8,9,10]"
λ> read it :: [Int]
[1,2,3,4,5,6,7,8,9,10]
tl;dr: cheap type parsing. For any more specialised/complex parsing,
use a proper parsing library like Parsec.
More information about the Beginners
mailing list