[Haskell-cafe] Why can `env` be assigned value two times ?
Brandon S. Allbery KF8NH
allbery at ece.cmu.edu
Sun Nov 15 19:04:49 EST 2009
On Nov 15, 2009, at 02:05 , zaxis wrote:
> defineVar :: Env -> (Id, Val) -> IOThrowsError Val
> defineVar envRef (id, val) = do {
> env <- liftIO $ readIORef envRef;
> env <- return $ filter (\(_id, _) -> _id/=id) env; -- clear the
> current
> scope
> valRef <- liftIO $ newIORef val;
> liftIO $ writeIORef envRef $ ((id, valRef):env);
> return val;
> }
>
> In haskell, the variable canot change its value , right? If so, why
> can the
> `env` be assigned value twice?
Because they're not really the same variable; they're separate lambda
bindings. If you translate the "do" syntax to the underlying "bind"
syntax, you get something like:
> defineVar envRef (id,val) =
> liftIO (readIORef envRef) >>=
> \env -> return (filter (\(_id,_) -> _id /= id) env) >>=
> \env -> liftIO (newIORef val) >>
> liftIO (writeIORef envRef ((id,valRef):env)) >>
> return val
So you're shadowing (hiding) the original "env" when you reuse the name.
--
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university KF8NH
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 195 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20091115/db2c070e/PGP.bin
More information about the Haskell-Cafe
mailing list