Haskell Prelude.read:不解析字符串 [英] Haskell Prelude.read: no parse String
问题描述
ghci>阅读5:: Int
5
ghci>阅读5:: Float
5.0
ghci> (读取5:: Float)* 4
20.0
ghci>阅读[1,2,3,4]:: [Int]
[1,2,3,4]
ghci>阅读(3,'a')::(Int,Char)
(3,'a')
但是当我尝试时
阅读asdf:: String
$ c
$ b $ p code读取asdf :: [Char]
我得到异常
< blockquote>
Prelude.read No Parse
我在这里做错了什么?
这是因为您拥有的字符串表示不是 String
的字符串表示形式,它需要引用嵌入字符串本身:
>阅读\asdf \:: String
asdf
是这样读取。显示=== id
用于字符串
:
>显示asdf
\asdf \
>阅读$ showasdf:: String
asdf
使用 Text.Read
中的 readMaybe
函数总是一个好主意:
> :t readMaybe
readMaybe :: Read a =>字符串 - >也许一个
> readMaybeasdf:: Maybe String
Nothing
> readMaybe\asdf \:: Maybe String
只是asdf
这可以避免(在我看来)破坏读取
函数,这会在解析失败时引发异常。
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?
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.
这篇关于Haskell Prelude.read:不解析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!