Skip to content

Instantly share code, notes, and snippets.

@MiyamonY
Created February 27, 2015 10:53
Show Gist options
  • Save MiyamonY/ba728f8ad946be743db9 to your computer and use it in GitHub Desktop.
Save MiyamonY/ba728f8ad946be743db9 to your computer and use it in GitHub Desktop.
import System.Environment
import System.Directory
import System.IO
import Data.List
import Control.Exception
dispatch :: String -> [String] -> IO ()
dispatch "add" = add
dispatch "view" = view
dispatch "remove" = remove
dispatch command = doesntExist command
doesntExist :: String -> [String] -> IO ()
doesntExist command _ =
putStrLn $ "The " ++ command ++ " command doesn't exist"
main = do
(command: argList) <- getArgs
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
contens <- readFile fileName
let todoTasks = lines contens
numberedTasks = zipWith (\ n line -> show n ++ " - " ++ line)
[0..] todoTasks
putStrLn $ unlines numberedTasks
remove :: [String] -> IO ()
remove [fileName, numberString] = do
contens <- readFile fileName
let todoTasks = lines contens
numberedTasks = zipWith (\ n line -> show n ++ " - " ++ line)
[0..] todoTasks
putStrLn "These are your TO-DO items: "
mapM_ putStrLn numberedTasks
let number = read numberString
newTodoItems = unlines $ delete (todoTasks !! number) todoTasks
bracketOnError (openTempFile "." "temp")
(\ (tempName, tempHandle) ->
hClose tempHandle
removeFile tempName)
(\ (tempName, tempHandle) ->
hPutStr tempHandle newTodoItems
hClose tempHandle
removeFile "todo.txt"
renameFile tempName "todo.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment