Skip to content

Instantly share code, notes, and snippets.

@acamino
Last active January 20, 2017 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acamino/c3d0ac395997a551b3e57450c0b89b73 to your computer and use it in GitHub Desktop.
Save acamino/c3d0ac395997a551b3e57450c0b89b73 to your computer and use it in GitHub Desktop.
TODO manager in Haskell
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