[Haskell-cafe] Language semantics
Jon Cast
jcast at ou.edu
Wed Jun 27 17:44:35 EDT 2007
On Wednesday 27 June 2007, Andrew Coppin wrote:
> Stefan O'Rear wrote:
> > On Wed, Jun 27, 2007 at 09:46:41PM +0100, Andrew Coppin wrote:
> >> I have a tricky little question...
> >>
> >> Suppose I write a function like this:
> >>
> >> foo pattern1
> >>
> >> | gard1 = ...
> >> | gard2 = ...
> >>
> >> foo pattern2
> >>
> >> | gard3 = ...
> >> | gard4 = ...
> >>
> >> According to one tutorial I read, if pattern1 matches, pattern2 will
> >> never be tried, even if both guard1 and guard2 fail.
> >>
> >> And according to another tutorial I read, if pattern1 matches but all
> >> guards fail, pattern2 *will* be tried.
> >>
> >> Can somebody comfirm which one is actually correct?
> >
> > According to http://haskell.org/onlinereport/exps.html#sect3.17.2
> >
> > Top level patterns in case expressions and the set of top level patterns
> > in function or pattern bindings may have zero or more associated guards.
> > A guard is a boolean expression that is evaluated only after all of
> > the arguments have been successfully matched, and it must be true for
> > the overall pattern match to succeed. The environment of the guard is
> > the same as the right-hand-side of the case-expression
> > alternative, function definition, or pattern binding to which it is
> > attached.
> >
> > So, if guard1 and guard2 both fail, then pattern1 doesn't match (and
> > pattern matching continues). As such, your "corner case" cannot
> > actually exist.
>
> Wow, wait a sec - case expressions are allowed to have guards too??
Yes. I guess I assumed you knew that, sorry.
The only syntactic (or semantic) difference between function equations and
case expressions (aside from the fact that case expressions require you to
tuple up the values you're pattern-matching on) is the fact that case
expressions use -> where function bindings use =. Other than that, the two
forms are exactly equivalent.
Sincerely,
Jonathan Cast
http://sourceforge.net/projects/fid-core
http://sourceforge.net/projects/fid-emacs
More information about the Haskell-Cafe
mailing list