[Haskell-cafe] Pattern Matching

John Dorsey haskell at colquitt.org
Thu Nov 12 21:30:38 EST 2009


Casey,

> Why in a pattern match like
> 
> score (1 3) = 7

You probably mean
> score 1 3 = 7

which applies the function 'score' to two arguments.  With the parentheses,
it looks like an application of '1' to the argument '3'.  But to answer your
actual question...

> can I not have
> 
> sizeMax = 3
> 
> score (1 sizeMax) = 7

When a variable name (such as 'sizeMax') appears in a pattern, it gets bound
there.  This is useful so you can refer to the variable on the right hand
side, as in:

successor x = x + 1

How would the compiler know whether to bind the variable (what actually
happens), or match against the value represented by some earlier binding
(what you're asking for)?

What if the type of that second argument doesn't have a defined equality
operation?

There might be some reasonable way to do it, but I suspect it would be
fragile and error-prone, at best.  So it's always a new binding.  It's easy
enough to work around:

score 1 x | x == sizeMax = 7

Regards,
John



More information about the Haskell-Cafe mailing list