`

haskell - Input and Output - Command Line

阅读更多

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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics