gpt4 book ai didi

haskell - `readMay` 和 `readMaybe` 有什么区别?

转载 作者:行者123 更新时间:2023-12-01 09:45:56 25 4
gpt4 key购买 nike

readMayreadMaybe 这两个函数具有相同的签名 Read a => 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

这里是 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

它们在中间错误消息上有所不同(readEitherSafe 显示了输入),但结果是相同的。


Safe 中的

readMay 早于 Text.Read 中的 readMaybe。除非您使用的 base 版本低于 4.6.0.0,否则请使用 Text.Read 中的 readMaybe,因为它不需要其他包。

关于haskell - `readMay` 和 `readMaybe` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48662019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com