Haskell使用什么类型的范围? [英] What type of scope does Haskell use?

查看:179
本文介绍了Haskell使用什么类型的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚Haskell是使用动态还是静态作用域。
我意识到,例如,如果您定义:

  let x = 10 

然后定义函数

  let square 2 = x * x 

你有两个不同的x's,这是否意味着它是动态范围?如果没有,它使用的范围是什么,为什么?

另外,Haskell变量是否有别名(同一个内存位置/值的名称不同)?



谢谢。

解决方案




  • Haskell中没有可变变量只是定义(或不​​可变变量)
  • 变量存储器location是一个在Haskell中不存在的概念



在您的示例中, x 不是不是在这个例子中,函数中的10只是square的一个参数,它可以取任何值(你可以指定类型),但在这种情况下。



以下是由 Curt Sampson 提供的别名示例:

  import Data.IORef 

main :: IO()
main = do x < - newIORef 0 - 将0写入x
readIO Ref x>> = print - x包含0
let y = x
readIORef y>> = print - y包含0
writeIORef x 42 - x
readIORef y>> = print - y包含42


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.

解决方案

There are some things wrong in your statements...

  • There are no mutable variables in Haskell just definitions (or immutable variables)
  • A variable memory location is a concept that do not exist in Haskell

In your example, x is not 10 in the function is just a argument to square, that can take any value (you can specify the type later) in this case 10 but just in this case.

Here is an example of aliases provided by Curt Sampson:

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

这篇关于Haskell使用什么类型的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆