Skip to content

Instantly share code, notes, and snippets.

@delirehberi
Created August 20, 2019 21:52
Show Gist options
  • Save delirehberi/ca4c11a3d5b3552abd46c4db2e16e0e3 to your computer and use it in GitHub Desktop.
Save delirehberi/ca4c11a3d5b3552abd46c4db2e16e0e3 to your computer and use it in GitHub Desktop.
todo.haskell
--my first real haskell app
import System.Environment
import System.Directory
import System.IO
import Data.List
dispatch :: [(String, [String] -> IO ())]
dispatch = [
("add",add),
("view",view),
("remove",remove)
]
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 (\n line -> show n ++ "-" ++ line) [0..] todoTasks
putStr $ unlines numberedTasks
remove :: [String] -> IO ()
remove [filename, numberString] = do
handle <- openFile filename ReadMode
(tempName, tempHandle) <- openTempFile "." "temp"
content <- hGetContents handle
let number = read numberString
todoTasks = lines content
newTodoItems = delete (todoTasks !! number) todoTasks
hPutStr tempHandle $ unlines newTodoItems
hClose tempHandle
hClose handle
removeFile filename
renameFile tempName filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment