4

I try to parse command line arguments in haskell.

Below is a sample code:

import System.Environment

work :: [Integer] -> Int
work (s:r:t:es) = length es

main :: IO ()
main = getArgs >>= putStrLn . show . work . (map read)

I execute it with:

./test 2 10 10 [7, 3, 5, 4, 4]

The output is 5 like expected. But if I replace length with sum and Int with Integer the execution raises the error

test: Prelude.read: no parse

Can someone explain how to do this?

1 Answer 1

6

The list returned by getArgs will look like this: ["2", "10", "10", "[7,", "3,", "5,", "4,", "4]"]. The first three of those strings are valid string representations of integers, but the others are not. So when you use read on those, you'll get an error.

The reason that you don't see an error when you calculate the length, is that length does not have to look at the values in the lists, so the reads are never evaluated.

In order to sum the values, however, they definitely do need to be evaluated. So that's why you get an exception then.

In order to fix your problem, you could either just change the format of the arguments to not include brackets and commas, or manually go through the arguments and remove the brackets and commas before you pass them to read.

Another alternative would be to concatenate the later arguments together, separated by spaces, (so you end up with "[7, 3, 5, 4, 4]") and then pass that as a single string to read with type [Integer].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.