Created
March 21, 2014 06:48
-
-
Save cohalz/9680908 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.Environment | |
import Data.List | |
import System.Directory | |
import System.IO | |
import Control.Exception | |
dispatch :: String -> [String] -> IO () | |
dispatch "add" = add | |
dispatch "view" = view | |
dispatch "remove" = remove | |
dispatch command = doesntExist command | |
main = do | |
args <- getArgs | |
case args of | |
[] -> putStrLn "todo needs one of add, view, remove command" | |
(command:argList) -> dispatch command argList | |
add :: [String] -> IO () | |
add [fileName,todoItem] = appendFile fileName (todoItem ++ "\n") | |
add _ = putStrLn "The add command takes exactly two arguments" | |
view :: [String] -> IO () | |
view [fileName] = do | |
contents <- readFile fileName | |
let todoTasks = lines contents | |
numberdTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks | |
putStr $ unlines numberdTasks | |
view _ = putStrLn "The view command takes exactly one argument" | |
remove :: [String] -> IO () | |
remove [fileName, numberString] = do | |
contents <- readFile fileName | |
let todoTasks = lines contents | |
numberdTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks | |
let number = read numberString | |
newTodoItems = unlines $ delete (todoTasks !! number) todoTasks | |
bracketOnError (openTempFile "." "temp") | |
(\(tempName,tempHandle) -> do | |
hClose tempHandle | |
removeFile tempName) | |
(\(tempName,tempHandle) -> do | |
hPutStr tempHandle newTodoItems | |
hClose tempHandle | |
removeFile fileName | |
renameFile tempName fileName) | |
remove _ = putStrLn "The remove command takes exactly two arguments" | |
doesntExist :: String -> [String] -> IO () | |
doesntExist command _ = | |
putStrLn $ "The " ++ command ++ " command doesn't exist" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment