Haskell: Bound variables within the where clause

What is the scope of the associated variable? Why can't I access this from inside the article? For example, in this example:

someFunc x y = do
  let a = x + 10
  b <- someAction y
  return subFunc
  where
    subFunc = (a * 2) + (b * 3)

Here subFunc can see a, but not b. Why can't I use the bound variable inside the where clause? Thank.

+3
source share
1 answer

Because it can lead to inconsistency. Imagine this code:

printName = do
  print fullName
  firstName <- getLine
  lastName <- getLine
  return ()
  where
    fullName = firstName ++ " " + lastName

This code does not work, and due to these situations, the use of related variables is limited to the part of the block dothat follows the actual binding. This becomes clear when the above code is discolored:

printName =
  print fullName >>
  getLine >>= (\ firstName ->
    getLine >>= (\ lastName ->
      return ()
    )
  )
  where
    fullName = firstName ++ " " ++ lastName

Here you can see that the variables firstNameand lastNameare not included in the scope of the proposal whereand that they can not be used in any of the definitions in this section.

+8
source

All Articles