Irrefutable patterns for the ignorant
- Magnus Therning
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:
= do
main putStrLn "Before"
<- getArgs
[arg1] 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:
= do
main 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]