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
| import System.Environment import System.Directory import System.IO import Data.List
main = do (command:args) <- getArgs let (Just action) = lookup command dispatch action args
add :: [String] -> IO () add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n")
view :: [String] -> IO () view [fileName] = do contents <- readFile fileName let todoTasks = lines contents numberedTasks = zipWith (\n line -> show n ++ ": " ++ line) [0..] todoTasks putStrLn $ unlines numberedTasks
remove :: [String] -> IO () remove [fileName, numberString] = do handle <- openFile fileName ReadMode (tempName, tempHandle) <- openTempFile "." "temp" contents <- hGetContents handle let number = read numberString todoTasks = lines contents newTodoTasks = delete (todoTasks !! number) todoTasks hPutStr tempHandle $ unlines newTodoTasks hClose handle hClose tempHandle removeFile fileName renameFile tempName fileName
dispatch :: [(String, [String] -> IO ())] dispatch = [ ("add", add), ("view", view), ("remove", remove) ]
|