Irrefutable patterns for the ignorant

A few days ago was the first time I ever saw some code like this:

~[arg] <- getArgs

I hadn’t come across irrefutable patterns (also called lazy patterns) in Haskell before and was of course curious. This is an attempt at illustrating the difference between lazy and non-lazy pattern matching. Here’s some code not using lazy pattern matching:

main = do
    putStrLn "Before"
    [arg1] <- getArgs
    putStrLn "After"
    putStrLn arg1

Running it, without giving it any argument, results in:

Before
pattern: user error (Pattern match failure in do expression at pattern.hs:9:4-9)

Here’s almost the same code, but with lazy pattern matching:

main = do
    putStrLn "Before"
    ~[arg1] <- getArgs
    putStrLn "After"
    putStrLn arg1

Running it, again without providing any argument, results in:

Before
After
pattern: pattern.hs:(7,7)-(11,16): Irrefutable pattern failed for pattern [arg1]
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>