import Control.Concurrent (forkIO)
import System.Environment (getArgs)
main= do
[a,b]<- getArgs
putStrLn $ "command line arguments: " ++ show [a,b]
When I compiled it, it was all right, but when I ran it,
it said "user error (Pattern match failure in do expression)", what is wrong here?
The problem is that you're pattern matching [a, b] on the return value of getArgs. If you run your program with anything other than 2 arguments, then the return value will not match the pattern [a, b]. So unless you run this program as
$ ./xie 1 2
command line arguments: ["1","2"]
It will throw an error. Instead, if you wrote your code
main = do
args <- getArgs
case args of
[a, b] -> putStrLn $ "command line arguments: " ++ show [a, b]
_ -> putStrLn "Invalid number of arguments"
then you would never fail on a pattern match.
The pattern [a,b] only matches a 2-element list, so if getArgs returns a list with a different number of elements, the match will fail.
When using do notation, when a match fails, the fail function is called, which in the case of IO causes a userError to be thrown.
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