Question about scope of 'let' and 'where'

Tom Pledger Tom.Pledger@peace.com
Tue, 18 Mar 2003 08:12:23 +1200


Graham Klyne writes:
 | In the function body (rhs):
 | 
 |      let
 |          { a = (e1) }
 |      in
 |         (e2)
 |         where
 |              { b = f a }
 :
 | <comment>
 :
 | I now see that use of 'where' is restricted to specific contexts.  I wonder 
 | if such restriction is needed?  The differences between let and where in 
 | Haskell are something I find to be confusing.
 | </comment>

Hi.

Other people have already replied confirming *that* the 'where' has a
broader scope than the 'let' in the rhs of a function.

Here's an example of *why* the broad 'where' scope can be useful: it
allows us to share definitions between a function body and its guard,
and among multiple guarded branches.  The following is from Hugs's
Prelude, and shows definitions being shared by two branches.

    floatProperFraction x
       | n >= 0      = (fromInteger m * fromInteger b ^ n, 0)
       | otherwise   = (fromInteger w, encodeFloat r n)
                       where (m,n) = decodeFloat x
                             b     = floatRadix x
                             (w,r) = quotRem m (b^(-n))

HTH.
Tom