[Haskell-cafe] Language semantics

Stefan O'Rear stefanor at cox.net
Wed Jun 27 17:32:48 EDT 2007


On Wed, Jun 27, 2007 at 10:28:05PM +0100, 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??

stefan at stefans:~$ ghci
Loading package base ... linking ... done.
   ___         ___ _
  / _ \ /\  /\/ __(_)
 / /_\// /_/ / /  | |    GHC Interactive, version 6.7.20070612, for Haskell 98.
/ /_\\/ __  / /___| |    http://www.haskell.org/ghc/
\____/\/ /_/\____/|_|    Type :? for help.

Prelude> case () of { () | True -> "x" }
"x"
Prelude> 

Stefan


More information about the Haskell-Cafe mailing list