Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `readMay` and `readMaybe`?

Tags:

haskell

The two functions readMay and readMaybe have the same signature Read a => String -> Maybe a.

Is there any difference between them? If so, what are they? Which of the two function should be preferred?

like image 824
marcosh Avatar asked Jan 18 '26 12:01

marcosh


1 Answers

There is no difference. Here's how readMay's defined:

-- | 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

And here is 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

They differ in the intermediate error message (readEitherSafe shows the input), but the result will be same.


readMay from Safe predates readMaybe from Text.Read. Unless you're on a base version less than 4.6.0.0, use readMaybe from Text.Read as it does not need another package.

like image 133
Zeta Avatar answered Jan 20 '26 23:01

Zeta