"let" vs. "where"
Hamilton Richards
ham@cs.utexas.edu
Wed, 20 Aug 2003 14:39:42 -0500
At 7:42 AM +0200 8/20/03, Jan Scheffczyk wrote:
>Hi Andrew,
>
>> let x = expensiveComputation foo in x + x
>>
>> I would certainly hope that expensiveComputation wasn't called twice,
>> and even though the language doesn't guarantee it, I have already
>> written code that assumed it.
>
>I always thought that there is a tiny difference between "let" and "where":
>Using "let" "expensiveComputation foo" might be computed twice (depending on
>the compiler?).
>But using:
>
> x + x
> where x = expensiveComputation foo
>
>should compute the value for x only once.
>Therefore, I always try to use "where" for common subexpressions.
>
>Please correct me if I'm wrong here.
The reserved word "let" introduces an expression (a
"let-expression"), but there's no such thing as a "where-expression".
The reserved word "where" can be used only in definitions.
For example,
3 + ((x + x) where x = expensiveComputation foo)
is invalid syntax, whereas
3 + let x = expensiveComputation foo in x + x
is OK.
And here's a use of "where" in a definition:
let z = x + x where x = 2 in z*5
That could have been written using only "let":
let z = let x = 2 in x + x where x = 2 in z*5
Watch out for the Hugs 98 command line-- it allows
z*5 where z = x + x where x = 2
but that's not a truly valid expression, because you can't embed it
in a larger expression:
2 + (z*5 where z = x + x where x = 2)
is properly identified as a syntax error.
Regards,
--Ham
--
------------------------------------------------------------------
Hamilton Richards, PhD Department of Computer Sciences
Senior Lecturer The University of Texas at Austin
512-471-9525 1 University Station C0500
Taylor Hall 5.138 Austin, Texas 78712-1188
ham@cs.utexas.edu hrichrds@swbell.net
------------------------------------------------------------------