In a Haskell tutorial I ran across the following code:
do [...]
let atom = [first] ++ rest
return $ case atom of
Note that the let
expression does not have an in
block. What is the scope of such a let
expression? The next line?
Description. let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.
let is block-scoped Hence when you try to access b outside of if block, an error occurs (as shown above in the program). Note: The variables declared inside a function will be function scoped for both var and let .
Summary. Variables are declared using the let keyword are block-scoped, are not initialized to any value, and are not attached to the global object.
The scope of a let variable is block scope. The scope of a const variable is block scope. It can be updated and re-declared into the scope. It can be updated but cannot be re-declared into the scope.
Simply put, it's scoped "from where it's written until the end of the do
".
Note that within a do
statement, let
is handled differently.
According to http://www.haskell.org/haskellwiki/Monads_as_computation#Do_notation , it is interpreted as follows:
do { let <decls> ; <stmts> }
= let <decls> in do { <stmts> }
The scope is the rest of the do
block.
See §3.14 of the Haskell Report (specifically, the fourth case in the translation block). (Yes, this is the section about do
blocks, because let
without in
is only valid inside a do
block, as Porges points out.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With