What type of scope does Haskell use?

2019-04-28 03:04发布

I'm trying to figure out if Haskell uses dynamic or static scoping. I realize that, for example, if you define:

let x = 10

then define the function

let square x = x*x

You have 2 different "x's", and does that mean it is dynamically scoped? If not, what scoping does it use, and why?

Also, can Haskell variables have aliases (a different name for the same memory location/value)?

Thanks.

9条回答
We Are One
2楼-- · 2019-04-28 03:45

Yes, Haskell has aliases. Try out this little program:

import Data.IORef

main :: IO ()
main = do x <- newIORef 0         -- write 0 into x
          readIORef x >>= print   -- x contains 0
          let y = x
          readIORef y >>= print   -- y contains 0
          writeIORef x 42         -- write 42 into x
          readIORef y >>= print   -- y contains 42
查看更多
Explosion°爆炸
3楼-- · 2019-04-28 03:46

In your example, the global definition of x is shadowed by the local definition of x. In Haskell, a variable's scope is determined by a static reading of the source code - this is called lexical scope, but can get something similar to dynamic scoping with implicit parameters (but that can lead to some unexpected behavior (I've read; never tried 'em myself)).

查看更多
地球回转人心会变
4楼-- · 2019-04-28 03:50

Haskell use (broadly speaking) exactly the same lexical scoping as most other languages.

eg.

x = 10

Results in a value referenced through x in the global scope, whereas

square x = x * x

will result in x being lexically scoped to the function square. It may help if you think of the above form being a syntactic nicety for:

square = \ x -> x * x

As to your other question i'm not sure what you mean by aliasing

查看更多
登录 后发表回答