implementation module StdIOMonad //Deze module verpakt StdFile in een monadische jas import StdFile import StdMonad import StdMaybeMonad :: IO a = IO (*World Filehandle -> *(a, *World, Filehandle)) :: Void = Void :: Filemode = Lees | Schrijf :: Filenaam :== String :: *Filehandle = None | FH *(Bool, Filemode, *File) toInt :: Filemode -> Int toInt Lees = FReadText toInt Schrijf = FWriteText Start world = read ////voer monadische I/O actie uit op de wereld: //doIO :: (IO a) *World -> *(a,*World) //doIO (IO f) world = f (world, Closed) // IO is een monad: instance return IO where return x = IO (\w fh = (x, w, fh)) //instance >>= IO where // (>>=) (IO f) g = IO(\w = let (a, w1) = f w in doIO (g a) w1) //lees regel van de console: read:: IO String read = IO (\w fh -> ("", w, fh)) /*//schrijf regel naar de console: write:: String -> IO Void write s = IO (\w = (Void, write` s w)) where write`:: String *World -> *World write` s world # (io, world) = stdio world # io = fwrites s world # (_, world) = fclose io = world //open de file met gegeven filenaam en mode: open:: Filenaam Filemode -> IO (Maybe Filehandle) open s m = IO (\w = let (f1, w1) = openfh` s m w in (f1, (w1, f1))) where openfh`:: Filenaam Filemode *World -> (Maybe Filehandle, *World) openfh` s m world # (ok, file, world) = fopen s (toInt m) world | ok = (Just (Open (m, file)), world) | otherwise = (Nothing, world) //sluit de file met gegeven filenaam: close:: Filehandle -> IO Bool close fh = IO (\w = let (b1, w1) = close` fh w in (b1, (w1, Closed))) where close`:: Filehandle *World -> (Bool, *World) close` Closed world = (False, world) close` (Open (_, file)) world = fclose file world //bepaal of het lezen van de file klaar is: eof:: Filehandle -> IO Bool eof fh = IO (\w = let (b1, w1) = eof` fh w in (b1, (w1, Closed))) where eof`:: Filehandle *World -> (Bool, *World) eof` Closed world = (world, False) eaf`(Open (_, file)) world = fclose file //lees een regel van een file: readline:: Filehandle -> IO (Maybe String) readline fh = IO (\w = let r1 = readline` fh w in r1) where readline`:: Filehandle *World -> (Maybe String, (*World, Filehandle)) readline` Closed world = (world, Nothing) readline` (Open (Schrijf, _)) world = (world, Nothing) readline` (Open (Lees, file)) world # (line, file) = sfreadline file = (Just line, (world, Open (Lees, file))) //schrijf een regel naar een file: writeline:: String Filehandle -> IO Bool writeline s fh = IO (\w = let r1 = writeline` s fh w in r1) where writeline`:: String Filehandle *World -> (Bool, (*World, Filehandle)) writeline` line Closed world = (False, (world, Closed)) writeline` line (Open (Lees, file)) world = (False, (world, (Open (Lees, file)))) writeline` line (Open (Schrijf, file)) world # file = fwrites line file = (True, (world, file))*/