Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning command line arguments to variables

Tags:

haskell

I need to convert my command line argument chars to Ints. I would like to assign each one to a variable and use them in my function. I have the following:

import System.Environment   

getIntArg :: IO Int
getIntArg = fmap (read . head) getArgs

main = do
    n <- getIntArg
    print n

However, it doesn't loop through all the arguments only printing one. Also, would I assign each one to a variable to use?

I'm new to FP.

like image 981
Fullmetal_Alchemist_Fan Avatar asked Mar 07 '26 21:03

Fullmetal_Alchemist_Fan


1 Answers

if you want to map all arguments to Ints you should use

getIntArgs :: IO [Int]
getIntArgs = fmap (map read) $ getArgs

or a bit shorter:

getIntArgs = map read <$> getArgs

instead.

This way you can do

main = do
    ns <- getIntArgs
    print ns

and then get the ones you are interested in with (!!) or if you know/expect at least a fixed number of Int - arguments with

(n1:n2:n3:_) <- getIntArgs

but of course you should maybe check the length first - also this will fail if the user decides to input things that cannot get parsed into Ints


So if you don't want to reinvent the wheel (which might be ok if you want to learn or only need a quick solution) you maybe want to look around and use a existing package - for example parseargs to do this for you

like image 73
Random Dev Avatar answered Mar 09 '26 12:03

Random Dev