本文介绍了Haskell Prelude.read:不解析字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 来自haskell示例 http://learnyouahaskell.com/types-and-typeclasses 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 $ b $ p code读取asdf :: [Char] 我得到异常 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-typeclassesghci> 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 tryread "asdf" :: String orread "asdf" :: [Char]I get exception Prelude.read No ParseWhat 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 readMaybereadMaybe :: Read a => String -> Maybe a> readMaybe "asdf" :: Maybe StringNothing> readMaybe "\"asdf\"" :: Maybe StringJust "asdf"This avoids the (in my opinion) broken read function which raises an exception on parse failure. 这篇关于Haskell Prelude.read:不解析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-10 23:12