Skip to content

Instantly share code, notes, and snippets.

@mizukmb
Created November 30, 2017 22:12
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 mizukmb/8cb99970ee19701fc3c34464dec3fdba to your computer and use it in GitHub Desktop.
Save mizukmb/8cb99970ee19701fc3c34464dec3fdba to your computer and use it in GitHub Desktop.
import Control.Exception
import Data.List
import System.Directory
import System.Environment
import System.IO
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, todoList] = appendFile fileName (todoList ++ "\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
contents <- readFile fileName
let todoTasks = lines contents
numberedTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks
putStrLn "These are your TODO items:"
mapM_ putStrLn numberedTasks
putStrLn "Which one do you want to delete?"
let number = read numberString
newTodoItems = unlines $ delete (todoTasks !! number) todoTasks
bracketOnError (openTempFile "." "temp")
(\(tempName, tempHandle) -> do
hClose tempHandle
removeFile tempName)
(\(tempName, tempHandle) -> do
hPutStr tempHandle newTodoItems
hClose tempHandle
removeFile "todo.txt"
renameFile tempName "todo.txt")
@mizukmb
Copy link
Author

mizukmb commented Nov 30, 2017

すごいHaskellたのしく学ぼう! 『第9章 もっと入力、もっと出力』より

@mizukmb
Copy link
Author

mizukmb commented Nov 30, 2017

$ ./todo view todo.txt
0 - Iron the dishes
1 - Dust the dog
$ ./todo add todo.txt "Pick up children from dry cleaners"
$ ./todo view todo.txt
0 - Iron the dishes
1 - Dust the dog
2 - Pick up children from dry cleaners
$ ./todo remove todo.txt 2
These are your TODO items:
0 - Iron the dishes
1 - Dust the dog
2 - Pick up children from dry cleaners
Which one do you want to delete?
$ ./todo view todo.txt
0 - Iron the dishes
1 - Dust the dog
$ ./todo viewfoobar todo.txt
The viewfoobar command doesn't exist

@mizukmb
Copy link
Author

mizukmb commented Nov 30, 2017

doesntExist 関数は少なくとも main の下に書いたほうが良かった

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment