Typo
[packages/base.git] / Text / Read.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE NoImplicitPrelude #-}
3
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : Text.Read
7 -- Copyright : (c) The University of Glasgow 2001
8 -- License : BSD-style (see the file libraries/base/LICENSE)
9 --
10 -- Maintainer : libraries@haskell.org
11 -- Stability : provisional
12 -- Portability : non-portable (uses Text.ParserCombinators.ReadP)
13 --
14 -- Converting strings to values.
15 --
16 -- The "Text.Read" library is the canonical library to import for
17 -- 'Read'-class facilities. For GHC only, it offers an extended and much
18 -- improved 'Read' class, which constitutes a proposed alternative to the
19 -- Haskell 2010 'Read'. In particular, writing parsers is easier, and
20 -- the parsers are much more efficient.
21 --
22 -----------------------------------------------------------------------------
23
24 module Text.Read (
25 -- * The 'Read' class
26 Read(..),
27 ReadS,
28
29 -- * Haskell 2010 functions
30 reads,
31 read,
32 readParen,
33 lex,
34
35 -- * New parsing functions
36 module Text.ParserCombinators.ReadPrec,
37 L.Lexeme(..),
38 lexP,
39 parens,
40 readListDefault,
41 readListPrecDefault,
42 readEither,
43 readMaybe
44
45 ) where
46
47 import GHC.Base
48 import GHC.Read
49 import Data.Either
50 import Data.Maybe
51 import Text.ParserCombinators.ReadP as P
52 import Text.ParserCombinators.ReadPrec
53 import qualified Text.Read.Lex as L
54
55 ------------------------------------------------------------------------
56 -- utility functions
57
58 -- | equivalent to 'readsPrec' with a precedence of 0.
59 reads :: Read a => ReadS a
60 reads = readsPrec minPrec
61
62 -- | Parse a string using the 'Read' instance.
63 -- Succeeds if there is exactly one valid result.
64 -- A 'Left' value indicates a parse error.
65 --
66 -- /Since: 4.6.0.0/
67 readEither :: Read a => String -> Either String a
68 readEither s =
69 case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of
70 [x] -> Right x
71 [] -> Left "Prelude.read: no parse"
72 _ -> Left "Prelude.read: ambiguous parse"
73 where
74 read' =
75 do x <- readPrec
76 lift P.skipSpaces
77 return x
78
79 -- | Parse a string using the 'Read' instance.
80 -- Succeeds if there is exactly one valid result.
81 --
82 -- /Since: 4.6.0.0/
83 readMaybe :: Read a => String -> Maybe a
84 readMaybe s = case readEither s of
85 Left _ -> Nothing
86 Right a -> Just a
87
88 -- | The 'read' function reads input from a string, which must be
89 -- completely consumed by the input process.
90 read :: Read a => String -> a
91 read s = either error id (readEither s)