Created
March 7, 2014 14:41
-
-
Save rikukissa/9412656 to your computer and use it in GitHub Desktop.
Haskell todo-app
This file contains 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 System.Directory | |
import System.IO | |
import Data.List | |
dispatch :: [(String, [String] -> IO ())] | |
dispatch = [ ("add", add) | |
, ("view", view) | |
, ("remove", remove) | |
, ("bump", bump) | |
] | |
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 (\num task -> show num ++ " - " ++ task) [0..] todoTasks | |
putStrLn $ unlines numberedTasks | |
remove :: [String] -> IO () | |
remove [filename, num] = do | |
handle <- openFile filename ReadMode | |
(tempName, tempHandle) <- openTempFile "." "temp" | |
contents <- hGetContents handle | |
let number = read num | |
todoTasks = lines contents | |
newTodoItems = delete (todoTasks !! number) todoTasks | |
hPutStr tempHandle $ unlines newTodoItems | |
hClose handle | |
hClose tempHandle | |
removeFile filename | |
renameFile tempName filename | |
bump :: [String] -> IO () | |
bump [filename, num] = do | |
handle <- openFile filename ReadMode | |
(tempName, tempHandle) <- openTempFile "." "temp" | |
contents <- hGetContents handle | |
let number = read num | |
todoTasks = lines contents | |
task = todoTasks !! number | |
newTodoItems = task : delete task todoTasks | |
hPutStr tempHandle $ unlines newTodoItems | |
hClose handle | |
hClose tempHandle | |
removeFile filename | |
renameFile tempName filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment