summaryrefslogtreecommitdiff
path: root/libraries/base
diff options
context:
space:
mode:
authorIavor S. Diatchki <diatchki@galois.com>2011-12-22 15:43:31 -0800
committerIavor S. Diatchki <diatchki@galois.com>2011-12-22 15:43:31 -0800
commitd5ead92698442c8d3bd6e69a40a85b72a55b4dcc (patch)
tree70b29eaf73d15545d28cb5b9244284da58b1ce49 /libraries/base
parentc0e32a32a3f20a9310e7321a8a96acfe0ef0d0f7 (diff)
downloadhaskell-d5ead92698442c8d3bd6e69a40a85b72a55b4dcc.tar.gz
Export "readEither" and add "readMaybe".
This commit implements the change discussed in the following thread on the Haskell libraries list: http://www.haskell.org/pipermail/libraries/2011-December/thread.html#17290 NOTE: This only implements the change for GHC, but the change makes sense for Hugs too... Perhaps we should simply re-implement 'readEither' in terms of 'reads'?
Diffstat (limited to 'libraries/base')
-rw-r--r--libraries/base/Text/Read.hs13
1 files changed, 13 insertions, 0 deletions
diff --git a/libraries/base/Text/Read.hs b/libraries/base/Text/Read.hs
index cea334b28a..88784ac90d 100644
--- a/libraries/base/Text/Read.hs
+++ b/libraries/base/Text/Read.hs
@@ -42,6 +42,8 @@ module Text.Read (
#ifdef __GLASGOW_HASKELL__
readListDefault, -- :: Read a => ReadS [a]
readListPrecDefault, -- :: Read a => ReadPrec [a]
+ readEither, -- :: Read a => String -> Either String a
+ readMaybe -- :: Read a => String -> Maybe a
#endif
) where
@@ -50,6 +52,7 @@ module Text.Read (
import GHC.Base
import GHC.Read
import Data.Either
+import Data.Maybe
import Text.ParserCombinators.ReadP as P
#endif
#if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
@@ -82,6 +85,9 @@ parens p = optional
reads :: Read a => ReadS a
reads = readsPrec minPrec
+-- | Parse a string using the 'Read' instance.
+-- Succeeds if there is exactly one valid result.
+-- A 'Left' value indicates a parse error.
readEither :: Read a => String -> Either String a
readEither s =
case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of
@@ -94,6 +100,13 @@ readEither s =
lift P.skipSpaces
return x
+-- | Parse a string using the 'Read' instance.
+-- Succeeds if there is exactly one valid result.
+readMaybe :: Read a => String -> Maybe a
+readMaybe s = case readEither s of
+ Left _ -> Nothing
+ Right a -> Just a
+
-- | The 'read' function reads input from a string, which must be
-- completely consumed by the input process.
read :: Read a => String -> a