[Haskell-cafe] let vs. where

David Roundy droundy at darcs.net
Tue Nov 13 17:03:34 EST 2007


On Tue, Nov 13, 2007 at 11:41:20AM -0800, Justin Bailey wrote:
> On Nov 13, 2007 10:56 AM, John Lato <jwlato at gmail.com> wrote:
> > I know there are several important differences between let-expressions
> > and where-clauses regarding scoping and the restriction of "where" to
> > a top-level definition.  However, frequently I write code in which
> 
> One place I find it useful is when there is  a common computed value
> that is used throughout a function definition. For example, imagine
> some function that uses the length of a list passed in:
> 
>   someFunction ls a b c = ... (length ls)
>      where
>        someAuxFunction x y = ... length ls ..
>        someOtherFunction x y = ... length ls ...
> 
> a where clause can capture that calculation, make sure it's only done
> once, and shared throughout the function definition:
>
>   someFunction ls a b c = ... listLen ...
>      where
>        listLen = length ls
>        someAuxFunction x y = ... listLen ...
>        someOtherFunction x y = ... listLen ...
> 
> Notice a let clause wouldn't do it above, because "length ls" is
> called inside other functions defined in the where clause. Of course
> everything could be moved to a "let" clause in the function body. At
> that point I think it's purely stylistic.

A let clause would work fine here:

someFunction ls a b c = let listLen = length ls
                            someAuxFunction x y = ... listLen ...
                            someOtherFunction x y = ... listLen ...
                        in
                        ... listLen ...

it's just that you don't want to mix let and where clauses, because then
things get confusing.  Even if it worked with both, noone would know the
binding rules.
-- 
David Roundy
Department of Physics
Oregon State University


More information about the Haskell-Cafe mailing list