【问题标题】:Haskell Prelude.read: no parse StringHaskell Prelude.read:没有解析字符串
【发布时间】:2018-02-09 20:23:31
【问题描述】:

来自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

我在这里做错了什么?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    这是因为您拥有的字符串表示不是String 的字符串表示,它需要在字符串本身中嵌入引号:

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

    这样read . show === id 对应String

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

    附带说明一下,使用Text.Read 中的readMaybe 函数总是一个好主意:

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

    这避免了(在我看来)损坏的 read 函数,该函数会在解析失败时引发异常。

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 2018-08-28
      • 2021-12-21
      • 2012-04-27
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多