-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIOPrimitives.hs
56 lines (44 loc) · 1.71 KB
/
IOPrimitives.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module IOPrimitives (
ioPrimitives,
load
) where
import IError
import IOHelpers
import LispVal
import Control.Monad.Error
import System.IO
ioPrimitives :: [(String, [LispVal] -> IOThrowsLispError LispVal)]
ioPrimitives =
[("apply", applyProc),
("open-input-file", makePort ReadMode),
("open-output-file", makePort WriteMode),
("close-input-port", closePort),
("close-output-port", closePort),
("read", readProc),
("write", writeProc),
("read-contents", readContents),
("read-all", readAll)]
apply (IOFunc func) args = func args
applyProc :: [LispVal] -> IOThrowsLispError LispVal
applyProc [func, LispList args] = apply func args
applyProc (func : args) = apply func args
makePort :: IOMode -> [LispVal] -> IOThrowsLispError LispVal
makePort mode [LispString filename _] =
liftM Port $ liftIO $ openFile filename mode
closePort :: [LispVal] -> IOThrowsLispError LispVal
closePort [Port port] = liftIO $ hClose port >> (return $ LispBool True)
closePort _ = return $ LispBool False
readProc :: [LispVal] -> IOThrowsLispError LispVal
readProc [] = readProc [Port stdin]
readProc [Port port] = (liftIO $ hGetLine port) >>= liftThrows . readExpr
writeProc :: [LispVal] -> IOThrowsLispError LispVal
writeProc [obj] = writeProc [obj, Port stdout]
writeProc [obj, Port port] =
liftIO $ hPrint port obj >> (return $ LispBool True)
readContents :: [LispVal] -> IOThrowsLispError LispVal
readContents [LispString filename _] =
liftM (flip LispString False) $ liftIO $ readFile filename
load :: String -> IOThrowsLispError [LispVal]
load filename = (liftIO $ readFile filename) >>= liftThrows . readExprList
readAll :: [LispVal] -> IOThrowsLispError LispVal
readAll [LispString filename _] = liftM LispList $ load filename