Command line is pretty all a necessity if you want to make a scritp or application that runs a terminal .
The System.Environment module has two cool I/O actions. One is getArgs, which has a type ofgetArgs :: IO [String] and is an I/O action that will get the arguments that the program was run with and have as its contained result a list with the arguments. getProgName has a type of getProgName :: IO String and is an I/O action that contains the program name.
-- file
-- todo.hs
-- descrpition:
-- shows how we can use todo_list_examples
import System.Environment
import System.Directory
import System.IO
import Data.List
dispatch :: [(String, [String] -> IO ())]
dispatch = [ ("add", add)
, ("view", view)
, ("remove", remove)
]
add :: [String] -> IO ()
add [fileName, todoItem] = appendFile fileName (todoItem ++ "\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
handle <- openFile fileName ReadMode
(tempName, tempHandle) <- openTempFile "." "temp"
contents <- hGetContents handle
let number = read numberString
todoTasks = lines contents
newTodoItems = delete (todoTasks !! number) todoTasks
hPutStr tempHandle $ unlines newTodoItems
hClose handle
hClose tempHandle
removeFile fileName
renameFile tempName fileName
main = do
(command : args) <- getArgs
let (Just action) = lookup command dispatch
action args
-- run with the following arguments
-- runhaskell todo.hs view todo.txt
本文介绍了一个使用Haskell编写的命令行待办事项应用程序。该程序通过命令行参数进行交互,支持添加、查看和删除待办事项。文章详细展示了如何利用System.Environment模块获取命令行参数,并通过具体的函数实现添加、查看和删除等功能。
6万+

被折叠的 条评论
为什么被折叠?



