[Haskell-cafe] Re: Pattern matching articles/explanations

Al Falloon afalloon at synopsys.com
Thu Aug 16 15:24:02 EDT 2007

Ian Duncan wrote:
> Hello everyone, I've been working on improving my Haskell knowledge, and 
> in doing so, I have read a little about as-patterns as well as some form 
> of pattern that uses "~" that I don't really understand. I suspect there 
> are even more lesser-known pattern matching expressions than just these, 
> but I don't have the stamina to decode the Haskell 98 Report. Are there 
> any articles anyone is aware of, or anything in the Haskell wiki that 
> covers the built-in pattern matching facilities pretty comprehensively? 
> I've looked in the Haskell wiki myself, but information on different 
> pattern matching abilities seems rather scattered and I'm not entirely 
> sure what I should be looking for.


That is the pattern section from "A Gentle Introduction to Haskell". It 
should be a lot more accessible than the report.

As to the specific reference: the ~pat is called an "irrefutable" 
pattern, which is an odd name because its primary purpose is to make the 
pattern lazy. For instance:

f ~(Just x) y z = if something_complicated y then x else z

In this case, the first parameter is not evaluated until x is demanded. 
In particular, unless (something_complicated y) is true it will not be 
demanded at all.

The reason is that its called irrefutable is that it always succeeds 
(which could lead to pattern match failure at run-time) because you 
can't check the pattern until you evaluate the parameter. For our 
particular example, that means that (f Nothing foo bar) will still 
match, and if (something_complicated foo) is true, then you will get a 
pattern match failure at runtime when x is demanded.

However, this is really useful if you only have one constructor, because 
it lets you deconstruct the value via a pattern and preserve the laziness.

As another piece of trivia. Let bound patterns are already lazy, so you 
never need ~ in an outer pattern of a let. I.e.

let Just x = foo

is the same as

let ~(Just x) = foo

More information about the Haskell-Cafe mailing list