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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With