-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.hs
51 lines (40 loc) · 1.22 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
-- Todo list manager
import Data.List
import System.Directory
import System.Environment
import System.IO
-- View
enumerate = zipWith (\i l -> show i ++ " - " ++ l) [1..]
viewTodos filename _ = do
content <- readFile filename
let todos = lines content
putStrLn $ "You have " ++ (show $ length todos) ++ " todo items:"
mapM_ putStrLn $ enumerate todos
-- Add
ensureEOL text
| "\n" `isSuffixOf` text = text
| otherwise = text ++ "\n"
addTodo filename [text] = appendFile filename (ensureEOL text)
-- Remove
deleteIndex i lst
| i < length lst = take i lst ++ drop (i+1) lst
| otherwise = error "deleteIndex: index too large"
removeTodo filename [index] = do
content <- readFile filename
let indexNo = (read index) - 1
todos = lines content
todos' = deleteIndex indexNo todos
(tmpFile, tmpHandle) <- openTempFile "." filename
hPutStr tmpHandle (unlines todos')
hClose tmpHandle
renameFile tmpFile filename
dispatch = [("view", viewTodos),
("add", addTodo),
("remove", removeTodo)
]
main = do
args <- getArgs
let (cmd:filename:xs) = args
(Just action) = lookup cmd dispatch
action filename xs
-- vi: set sts=4 sw=4 et :