r.sendecky
r.sendecky

Reputation: 10353

Haskell: Bound variables within where clause

What is the scope of a bound variable? Why can't I access it from within where clause? For instance, in this example:

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

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

Upvotes: 3

Views: 252

Answers (1)

dflemstr
dflemstr

Reputation: 26147

Because it could lead to inconsistencies. Imagine this code:

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

This code wouldn't work, and because of these kinds of situations, the use of bound variables is limited to the part of a do block that follows the actual binding. This becomes clear when desugaring the above code:

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

Here, one can see that the variables firstName and lastName are not in scope in the where clause, and that they cannot be used in any definitions in that clause.

Upvotes: 8

Related Questions