Last active
January 20, 2017 12:33
-
-
Save acamino/c3d0ac395997a551b3e57450c0b89b73 to your computer and use it in GitHub Desktop.
TODO manager in Haskell
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.Directory | |
import System.Environment | |
import System.IO | |
import Control.Monad | |
import Data.List | |
dispatch :: [(String, [String] -> IO ())] | |
dispatch = [ ("add", add) | |
, ("view", view) | |
, ("remove", remove) | |
, ("bump", bump) | |
] | |
main = do | |
(command:args) <- getArgs | |
let action = lookup command dispatch | |
case action of | |
Just handler -> handler args | |
Nothing -> errorExit | |
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 | |
mapM_ putStrLn 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 | |
mapM_ (hPutStrLn tempHandle) newTodoTasks | |
hClose handle | |
hClose tempHandle | |
removeFile fileName | |
renameFile tempName fileName | |
bump :: [String] -> IO () | |
bump [fileName, numberString] = do | |
handle <- openFile fileName ReadMode | |
(tempName, tempHandle) <- openTempFile "." "temp" | |
contents <- hGetContents handle | |
let number = read numberString | |
todoTasks = lines contents | |
selectedTask = todoTasks !! number | |
newTodoTasks = [selectedTask] ++ (delete selectedTask todoTasks) | |
mapM_ (hPutStrLn tempHandle) newTodoTasks | |
hClose handle | |
hClose tempHandle | |
removeFile fileName | |
renameFile tempName fileName | |
errorExit :: IO () | |
errorExit = do | |
putStrLn "Unrecognized option" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment