Wednesday, 27 May 2015

Echo the Command Line Arguments

ok another little toy: echo the command line arguments back to the terminal:-

module Main

import System.Environment(getArgs)

main = do
  args <- getArgs
  mapM_ putStrLn args

This time we want the function getArgs from the library System.Environment

This has type

getArgs :: IO [String]

so naturally enough we get a list of strings back when the action is performed.

The IO action that writes to the string, function putStrLn, has the type:

putStrLn :: String -> IO ()

So this takes a string and gives you back the IO action that writes to the terminal but does not return any value.  We want to apply this to a list of strings and get an IO action that will write all of them to the terminal.  As before this is a job for mapM_, which has the type:

mapM_ :: Monad m => (a -> m b) -> [a] -> m ()

The (a -> m b) corresponds to our String -> IO ()  and the [a] bit to our [String]

I know I'm labouring this a bit but I want to get it clear in my head.  So let's call the resulting program echoargs:

>ghc main.hs -o echoargs.exe
Linking echoargs.exe ...

>echoargs curly larry moe

No comments:

Post a Comment