Haskell “readMay”和“readMay”有什么区别?
两个函数Haskell “readMay”和“readMay”有什么区别?,haskell,Haskell,两个函数readMay和readMaybe具有相同的签名reada=>String->Maybe a 他们之间有什么区别吗?如果是,它们是什么?这两个功能中哪一个应该是首选的?没有区别。以下是readMay的定义: -- | This function provides a more precise error message than 'readEither' from 'base'. readEitherSafe :: Read a => String -> Either Str
readMay
和readMaybe
具有相同的签名reada=>String->Maybe a
他们之间有什么区别吗?如果是,它们是什么?这两个功能中哪一个应该是首选的?没有区别。以下是
readMay
的定义:
-- | This function provides a more precise error message than 'readEither' from 'base'.
readEitherSafe :: Read a => String -> Either String a
readEitherSafe s = case [x | (x,t) <- reads s, ("","") <- lex t] of
[x] -> Right x
[] -> Left $ "no parse on " ++ prefix
_ -> Left $ "ambiguous parse on " ++ prefix
where
maxLength = 15
prefix = '\"' : a ++ if length s <= maxLength then b ++ "\"" else "...\""
where (a,b) = splitAt (maxLength - 3) s
readMay :: Read a => String -> Maybe a
readMay = eitherToMaybe . readEitherSafe
它们在中间错误消息中有所不同(readEitherSafe
显示输入),但结果相同
readMay
fromSafe
早于readMay
fromText.Read
。除非您的基础版本低于4.6.0.0,否则请使用文本中的readMaybe
。阅读,因为它不需要另一个软件包。我是否确认一个在安全中,另一个在文本中。阅读模块?是的,您是正确的
-- | Parse a string using the 'Read' instance.
-- Succeeds if there is exactly one valid result.
-- A 'Left' value indicates a parse error.
--
-- @since 4.6.0.0
readEither :: Read a => String -> Either String a
readEither s =
case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of
[x] -> Right x
[] -> Left "Prelude.read: no parse"
_ -> Left "Prelude.read: ambiguous parse"
where
read' =
do x <- readPrec
lift P.skipSpaces
return x
-- | Parse a string using the 'Read' instance.
-- Succeeds if there is exactly one valid result.
--
-- @since 4.6.0.0
readMaybe :: Read a => String -> Maybe a
readMaybe s = case readEither s of
Left _ -> Nothing
Right a -> Just a