Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Prelude.read: no parse String

Tags:

haskell

from haskell examples http://learnyouahaskell.com/types-and-typeclasses

ghci> read "5" :: Int   5   ghci> read "5" :: Float   5.0   ghci> (read "5" :: Float) * 4   20.0   ghci> read "[1,2,3,4]" :: [Int]   [1,2,3,4]   ghci> read "(3, 'a')" :: (Int, Char)   (3, 'a')   

but when I try

read "asdf" :: String  

or

read "asdf" :: [Char] 

I get exception

Prelude.read No Parse

What am I doing wrong here?

like image 960
Herokiller Avatar asked Jan 14 '15 16:01

Herokiller


1 Answers

This is because the string representation you have is not the string representation of a String, it needs quotes embedded in the string itself:

> read "\"asdf\"" :: String "asdf" 

This is so that read . show === id for String:

> show "asdf" "\"asdf\"" > read $ show "asdf" :: String "asdf" 

As a side note, it's always a good idea to instead use the readMaybe function from Text.Read:

> :t readMaybe readMaybe :: Read a => String -> Maybe a > readMaybe "asdf" :: Maybe String Nothing > readMaybe "\"asdf\"" :: Maybe String Just "asdf" 

This avoids the (in my opinion) broken read function which raises an exception on parse failure.

like image 131
bheklilr Avatar answered Nov 08 '22 21:11

bheklilr