Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"User error" pattern matching failure when using getArgs

Tags:

haskell

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?

like image 701
Xie Avatar asked Aug 01 '26 21:08

Xie


2 Answers

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.

like image 51
bheklilr Avatar answered Aug 04 '26 20:08

bheklilr


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.

like image 40
Lee Avatar answered Aug 04 '26 20:08

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!