guru107
guru107

Reputation: 1143

Does the 'it' variable in GHCi Haskell mutate?

Just started with Haskell and it is said that Haskell has immutable variables. Then why does 'it' variable keep mutating its value every time an expression is entered in GHCi prompt?

GHCi, version 7.10.2: http://www.haskell.org/ghc/  :? for help
Prelude> 7*2
14
Prelude> it
14
Prelude> "foo"
"foo"
Prelude> it
"foo"
Prelude>

Upvotes: 0

Views: 152

Answers (1)

Paul Johnson
Paul Johnson

Reputation: 17786

Expressions typed into ghci have an implicit type of

it :: (Show a) => IO a

In other words everything you do is in the IO monad (the "Show" means you have to be able to convert the result to text for printing). When you type a series of expressions in, it works like this:

do
   it <- foo
   it <- bar

Haskell's "do" notation desugars into nested lambdas something like this

  foo >>= $ \it ->
     bar >>= $ \it -> ... -- and so on.

In other words the value of "it" is not changing, rather a new value is being declared in a scope that shadows the previous one.

Upvotes: 8

Related Questions