Remove Hugs98 specific code
[packages/base.git] / Text / Read.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE CPP, 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 #ifdef __GLASGOW_HASKELL__
36 -- * New parsing functions
37 module Text.ParserCombinators.ReadPrec,
38 L.Lexeme(..),
39 lexP,
40 parens,
41 #endif
42 #ifdef __GLASGOW_HASKELL__
43 readListDefault,
44 readListPrecDefault,
45 readEither,
46 readMaybe
47 #endif
48
49 ) where
50
51 #ifdef __GLASGOW_HASKELL__
52 import GHC.Base
53 import GHC.Read
54 import Data.Either
55 import Data.Maybe
56 import Text.ParserCombinators.ReadP as P
57 #endif
58 #ifdef __GLASGOW_HASKELL__
59 import Text.ParserCombinators.ReadPrec
60 import qualified Text.Read.Lex as L
61 #endif
62
63 #ifdef __GLASGOW_HASKELL__
64 ------------------------------------------------------------------------
65 -- utility functions
66
67 -- | equivalent to 'readsPrec' with a precedence of 0.
68 reads :: Read a => ReadS a
69 reads = readsPrec minPrec
70
71 -- | Parse a string using the 'Read' instance.
72 -- Succeeds if there is exactly one valid result.
73 -- A 'Left' value indicates a parse error.
74 readEither :: Read a => String -> Either String a
75 readEither s =
76 case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of
77 [x] -> Right x
78 [] -> Left "Prelude.read: no parse"
79 _ -> Left "Prelude.read: ambiguous parse"
80 where
81 read' =
82 do x <- readPrec
83 lift P.skipSpaces
84 return x
85
86 -- | Parse a string using the 'Read' instance.
87 -- Succeeds if there is exactly one valid result.
88 readMaybe :: Read a => String -> Maybe a
89 readMaybe s = case readEither s of
90 Left _ -> Nothing
91 Right a -> Just a
92
93 -- | The 'read' function reads input from a string, which must be
94 -- completely consumed by the input process.
95 read :: Read a => String -> a
96 read s = either error id (readEither s)
97 #endif
98