Haskell Prelude.read: no parse String

前端 未结 1 764
[愿得一人]
[愿得一人] 2021-02-03 23:49

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

ghci> read \"5\" :: Int  
5  
ghci> read \"5\" :: Float  
5.0  
ghci> (read \"5\         


        
1条回答
  •  滥情空心
    2021-02-04 00:14

    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.

    0 讨论(0)
提交回复
热议问题