-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.hs
61 lines (52 loc) · 1.63 KB
/
todo.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
{- Todo program. Maintains a file called todo.txt.
- Usage:
- todo [list]
- todo [Thing to be done]
- todo done #
-}
import System.Directory
import System.Environment
import System.IO
import Data.List
fileName = "todo.txt"
main = do
args <- getArgs
dispatch args
dispatch :: [String] -> IO ()
dispatch [] = cmdList
dispatch ["list"] = cmdList
dispatch ("list":_) = error "list takes no arguments"
dispatch ["bump", num] = cmdBump $ read num
dispatch ("bump":_) = error "usage: bump <number>"
dispatch ["done", num] = cmdDone $ read num
dispatch ("done":_) = error "usage: done <number>"
dispatch todoText = cmdTodo $ unwords todoText
cmdList :: IO ()
cmdList = do
todo <- readFile fileName
let todoTasks = lines todo
numberedTasks = zipWith (\n line -> show n ++ ". " ++ line) [1..] todoTasks
putStr $ unlines numberedTasks
cmdDone :: Int -> IO ()
cmdDone num = rewriteTodo (removeIndex (num-1))
cmdBump :: Int -> IO ()
cmdBump num = rewriteTodo (bumpToTop (num-1))
where bumpToTop n list = (list !! n) : (removeIndex n list)
cmdTodo :: String -> IO ()
cmdTodo thing = do
appendFile fileName (thing ++ "\n")
cmdList
rewriteTodo :: ([String] -> [String]) -> IO ()
rewriteTodo rewriteFunc = do
handle <- openFile fileName ReadMode
(tempName, tempHandle) <- openTempFile "." "temp"
contents <- hGetContents handle
let todoTasks = lines contents
newTodoItems = rewriteFunc todoTasks
hPutStr tempHandle $ unlines newTodoItems
hClose handle
hClose tempHandle
removeFile fileName
renameFile tempName fileName
cmdList
removeIndex n list = (take n list) ++ (drop (n+1) list)