OCaml 中的不可变变量 [英] Immutable variables in OCaml
本文介绍了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:
- 将
42
绑定到名称foo
. - 创建一个函数
return_foo ()
返回绑定到foo
的值. - 将
24
绑定到名称foo
(隐藏了之前的foo
绑定). - 调用
return_foo()
函数,返回42
.
- Binds
42
to the namefoo
. - Creates a function
return_foo ()
that returns the value bound tofoo
. - Binds
24
to the namefoo
(which hides the previous binding offoo
). - Calls the
return_foo ()
function, which returns42
.
将此与可变值的行为(在 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
哪个:
- 创建一个包含
42
的可变引用并将其绑定到名称foo
. - 创建一个函数
return_foo ()
返回存储在绑定到foo
的引用中的值. - 将
24
存储在绑定到foo
的引用中. - 调用
return_foo()
函数,返回24
.
- Creates a mutable reference containing
42
and binds it to the namefoo
. - Creates a function
return_foo ()
that returns the value stored in the reference bound tofoo
. - Stores
24
in the reference bound tofoo
. - Calls the
return_foo ()
function, which returns24
.
这篇关于OCaml 中的不可变变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文