[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / interpreter / prelude / PreludeIO.hs
1 #ifdef HEAD
2 module PreludeIO (
3     FilePath, IOError, fail, userError, catch,
4     putChar, putStr, putStrLn, print,
5     getChar, getLine, getContents, interact,
6     readFile, writeFile, appendFile, readIO, readLn
7   ) where
8
9 import PreludeBuiltin
10 #endif /* HEAD */
11 #ifdef BODY
12
13 #if STD_PRELUDE
14 type  FilePath = String
15
16 data IOError    -- The internals of this type are system dependent
17
18 instance  Show IOError  where ...
19 instance  Eq IOError  where ...
20 #endif
21
22 #if STD_PRELUDE
23 fail             ::  IOError -> IO a 
24 fail             =   primFail
25
26 userError        ::  String -> IOError
27 userError        =   primUserError
28
29 catch            ::  IO a -> (IOError -> IO a) -> IO a 
30 catch            =   primCatch
31 #else
32 #endif
33
34 #if STD_PRELUDE
35 #else
36 -- this guy can go in either monad
37 primFail         :: Exception -> ST s a 
38 primFail err     =  ST (\ s -> primRaise err)
39 #endif
40
41 #if STD_PRELUDE
42 putChar          :: Char -> IO ()
43 putChar          =  primPutChar
44
45 putStr           :: String -> IO ()
46 putStr s         =  mapM_ putChar s
47
48 putStrLn         :: String -> IO ()
49 putStrLn s       =  do putStr s
50                        putStr "\n"
51
52 print            :: Show a => a -> IO ()
53 print x          =  putStrLn (show x)
54
55 getChar          :: IO Char
56 getContents      =  primGetChar
57
58 getLine          :: IO String
59 getLine          =  do c <- getChar
60                        if c == '\n' then return "" else 
61                           do s <- getLine
62                              return (c:s)
63             
64 getContents      :: IO String
65 getContents      =  primGetContents
66
67 interact         ::  (String -> String) -> IO ()
68 interact f       =   do s <- getContents
69                         putStr (f s)
70
71 readFile         :: FilePath -> IO String
72 readFile         =  primReadFile
73
74 writeFile        :: FilePath -> String -> IO ()
75 writeFile        =  primWriteFile
76
77 appendFile       :: FilePath -> String -> IO ()
78 appendFile       =  primAppendFile
79 #endif
80
81   -- raises an exception instead of an error
82 readIO           :: Read a => String -> IO a
83 readIO s         =  case [x | (x,t) <- reads s, ("","") <- lex t] of
84                          [x] -> return x
85                          []  -> fail (userError "PreludeIO.readIO: no parse")
86                          _   -> fail (userError 
87                                        "PreludeIO.readIO: ambiguous parse")
88
89 #if STD_PRELUDE
90 readLn           :: Read a => IO a
91 readLn           =  do l <- getLine
92                        r <- readIO l
93                        return r
94 #endif
95
96 #endif /* BODY */