Running my program with command line arguments

I am attempting to run my program using the command line. I am trying to return my command line arguments:

import System.Environment   
import Data.List  

main :: IO()

main = do  
   args <- getArgs  
   progName <- getProgName  
   putStrLn "The arguments are:"  
   mapM putStrLn args  
   putStrLn "The program name is:"  
   putStrLn progName  

I am executing the code by calling the main function with my arguments:

main argument arguments "more arguements"

However, I am getting a complier error:

<interactive>:33:6: Not in scope: ‘argument’
<interactive>:33:15: Not in scope: ‘arguments’

Is there an issue with how I am calling my function with my arguments?

Upvotes: 3

Views: 666

Answers (1)

Zeta
Zeta

Reputation: 105935

You have to use :main if you want to simulate command line arguments. main alone only executes your IO () action, but doesn't actually build the arguments. For all what GHCi knows, main doesn't necessarily need to be IO (), it could be Int -> Int -> IO ().

However, if you use :main, GHC will use main in the same way it would get invoked during an runhaskell call, e.g. with interpreting the following parameters as command line arguments.

Alternatively, you can use withArgs from System.Environment:

ghci> withArgs ["argument", "arguments", "more arguments"] main

Upvotes: 10

Related Questions