-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.hs
39 lines (31 loc) · 1.25 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
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 numberedTasks = zipWith (\n t -> show n ++ "-" ++ t) [0 ..] $ lines contents
putStr $ unlines numberedTasks
remove :: [String] -> IO ()
remove [fileName, strNum] = do
contents <- readFile fileName
(tName, tHandle) <- openTempFile "." "temp"
let todolines = lines contents
number = read strNum
newToDoList = delete (todolines !! number) todolines
hPutStr tHandle $ unlines newToDoList
hClose tHandle
removeFile fileName
renameFile tName fileName