From f420756edea1ebbe8b6a2dfaf62e1907ec3d6aa3 Mon Sep 17 00:00:00 2001 From: Camil Staps Date: Sat, 18 Apr 2015 22:32:29 +0200 Subject: [PATCH] SimpleFileIO: readFile, readLines, writeFile, writeLines --- fp2/week1/camil/SimpleFileIO.dcl | 14 ++++++++++++ fp2/week1/camil/SimpleFileIO.icl | 39 ++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 fp2/week1/camil/SimpleFileIO.dcl create mode 100644 fp2/week1/camil/SimpleFileIO.icl diff --git a/fp2/week1/camil/SimpleFileIO.dcl b/fp2/week1/camil/SimpleFileIO.dcl new file mode 100644 index 0000000..5e38af3 --- /dev/null +++ b/fp2/week1/camil/SimpleFileIO.dcl @@ -0,0 +1,14 @@ +definition module SimpleFileIO + +import StdFile, StdOverloaded, StdMaybe + +// 1. +//readFile :: String *env -> (Maybe String, *env) | FileSystem env +//writeFile :: String String *env -> (Bool, *env) | FileSystem env + +// 2. +readLines :: String *env -> (Maybe [String],*env) | FileSystem env +//writeLines :: String [String] *env -> (Bool, *env) | FileSystem env + +// 3. +//mapFile :: String String (a -> b) *env -> (Bool, *env) | FileSystem env & ... a & ... b diff --git a/fp2/week1/camil/SimpleFileIO.icl b/fp2/week1/camil/SimpleFileIO.icl new file mode 100644 index 0000000..b2a483a --- /dev/null +++ b/fp2/week1/camil/SimpleFileIO.icl @@ -0,0 +1,39 @@ +implementation module SimpleFileIO + +import StdEnv, StdFile, StdOverloaded, StdMaybe + +// 1. +readFile :: String *env -> (Maybe String, *env) | FileSystem env +readFile s env +# (ss, env) = readLines s env +| ss == Nothing = (Nothing, env) +| otherwise = (Just (foldl (+++) "" (fromJust ss)), env) + +writeFile :: String String *env -> (Bool, *env) | FileSystem env +writeFile fn s env +# (ok, outfile, env) = fopen fn FWriteText env +| not ok = (False, env) +# outfile = fwrites s outfile +# (ok, env) = fclose outfile env +| otherwise = (ok, env) + +// 2. +readLines :: String *env -> (Maybe [String],*env) | FileSystem env +readLines s env +# (ok, infile, env) = sfopen s FReadText env +| not ok = (Nothing, env) +| otherwise = (Just (fst (readLines` infile)), env) +where + readLines` :: File -> ([String], File) + readLines` file + | sfend file = ([], file) + # (line, file) = sfreadline file + # (ss, file) = readLines` file + | otherwise = ([line : ss], file) + +writeLines :: String [String] *env -> (Bool, *env) | FileSystem env +writeLines fn ss env = writeFile fn (foldl (+++) "" [s +++ "\n" \\ s <- ss]) env + +// 3. +//mapFile :: String String (a -> b) *env -> (Bool, *env) | FileSystem env & ... a & ... b + -- 2.20.1