Haskell 命令行参数

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
import System.Environment
import System.Directory
import System.IO
import Data.List

main = do
(command:args) <- getArgs -- get the command
let (Just action) = lookup command dispatch -- find the command
action args -- do something

add :: [String] -> IO ()
add [fileName, todoItem] = appendFile fileName (todoItem ++ "\n") -- add the todoItem

view :: [String] -> IO ()
view [fileName] = do -- match the filename
contents <- readFile fileName -- read the file
let todoTasks = lines contents -- get the contents
numberedTasks = zipWith (\n line -> show n ++ ": " ++ line) [0..] todoTasks
putStrLn $ unlines numberedTasks -- show the items

remove :: [String] -> IO ()
remove [fileName, numberString] = do -- get the filename and the line number
handle <- openFile fileName ReadMode
(tempName, tempHandle) <- openTempFile "." "temp" -- create a temp file
contents <- hGetContents handle -- get contents from the handle
let number = read numberString -- read the String to Number
todoTasks = lines contents
newTodoTasks = delete (todoTasks !! number) todoTasks -- remove the line of the number
hPutStr tempHandle $ unlines newTodoTasks -- putStr into the tempfile
hClose handle -- close handles
hClose tempHandle
removeFile fileName
renameFile tempName fileName

dispatch :: [(String, [String] -> IO ())]
dispatch = [
("add", add),
("view", view),
("remove", remove)
]

-- runhaskell arags-test.hs view newData.txt
-- runhaskell args-test.hs add newData.txt "Say Hello"
-- runhaskell args-test.hs remove newData.txt 4