来自haskell示例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')
但是当我尝试
时read "asdf" :: String
或
read "asdf" :: [Char]
我得到例外
Prelude.read No Parse
我在这里做错了什么?
答案 0 :(得分:37)
这是因为您拥有的字符串表示形式不是String
的字符串表示形式,它需要嵌入字符串本身的引号:
> read "\"asdf\"" :: String
"asdf"
这是read . show === id
的{{1}}:
String
作为旁注,最好使用> show "asdf"
"\"asdf\""
> read $ show "asdf" :: String
"asdf"
中的readMaybe
函数:
Text.Read
这避免了(在我看来)破解> :t readMaybe
readMaybe :: Read a => String -> Maybe a
> readMaybe "asdf" :: Maybe String
Nothing
> readMaybe "\"asdf\"" :: Maybe String
Just "asdf"
函数,这会在解析失败时引发异常。