OCaml 中的不可变变量 [英] Immutable variables in OCaml

查看:49
本文介绍了OCaml 中的不可变变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 OCaml,我对变量的不变性有点困惑.根据我正在阅读的书,变量是不可变的.到目前为止一切顺利,但为什么我能做到这一点:

I'm learning OCaml, and I'm a bit confused with the immutability of variables. According to the book I'm reading, variables are immutable. So far so good, but why on Earth can I do this:

let foo = 42
let foo = 4242

我错过了什么??

推荐答案

我认为最好的解释方式是举例.考虑以下代码(在 OCaml REPL 中执行):

I think the best way to explain is with an example. Consider this code (executed in the OCaml REPL):

# let foo = 42;;
val foo : int = 42

# let return_foo () = foo;;
val return_foo : unit -> int = <fun>

# let foo = 24;;
val foo : int = 24

# return_foo ();;
- : int = 42

以上代码执行以下操作:

The above code does the following:

  1. 42 绑定到名称 foo.
  2. 创建一个函数 return_foo () 返回绑定到 foo 的值.
  3. 24 绑定到名称 foo(隐藏了之前的 foo 绑定).
  4. 调用return_foo()函数,返回42.
  1. Binds 42 to the name foo.
  2. Creates a function return_foo () that returns the value bound to foo.
  3. Binds 24 to the name foo (which hides the previous binding of foo).
  4. Calls the return_foo () function, which returns 42.

将此与可变值的行为(在 OCaml 中使用 ref 创建)进行比较:

Compare this with the behaviour of a mutable value (created using ref in OCaml):

# let foo = ref 42;;
val foo : int ref = {contents = 42}

# let return_foo () = !foo;;
val return_foo : unit -> int = <fun>

# foo := 24;;
- : unit = ()

# return_foo ();;
- : int = 24

哪个:

  1. 创建一个包含 42 的可变引用并将其绑定到名称 foo.
  2. 创建一个函数 return_foo () 返回存储在绑定到 foo 的引用中的值.
  3. 24 存储在绑定到 foo 的引用中.
  4. 调用return_foo()函数,返回24.
  1. Creates a mutable reference containing 42 and binds it to the name foo.
  2. Creates a function return_foo () that returns the value stored in the reference bound to foo.
  3. Stores 24 in the reference bound to foo.
  4. Calls the return_foo () function, which returns 24.

这篇关于OCaml 中的不可变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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