无法理解函数体内F#可变变量的逻辑 [英] Can't understand the logic of F# mutable variable inside function body
问题描述
我正在学习F#,并陷入了mutable
关键字的概念.
I'm learning F# and get stuck with the concept of mutable
keyword.
请参见以下示例:
let count =
let mutable a = 1
fun () -> a <- a + 1; a
val count: unit -> int
每次用()
调用时,该值增加1.但是下一个代码没有:
Which increases by 1 every time it's called with ()
. But next code does not:
let count =
let mutable a = 1
a <- a + 1
a
val count: int
始终是2
.
在我正在学习的书中,它用第一个示例说:当函数第一次调用时,可变值a
的初始化仅进行一次."
In the book I'm studying with, it says with the first example, "The initialization of mutable value a
is done only once, when the function has called first time."
当我开始使用haskell学习FP时,它处理这种副作用的方式完全烧伤了我的大脑,但是F#mutable
却以另一种方式再次破坏了我的大脑.以上两个摘要有什么区别?而且,关于可变值的初始化,以上句子的真正含义和条件是什么?
When I started learning FP with haskell, the way it handled side effects like this totally burnt my brain, but F# mutable
is destroying my brain again, with a different way. What's the difference between above two snippets? And, what's the true meaning and condition of above sentence, about the initialization of mutable value?
推荐答案
第二个示例
let count =
let mutable a = 1
a <- a + 1
a
定义一个初始化为1的可变变量,然后使用<-
运算符为其分配新值(a + 1),然后在最后一行返回更新的值.由于a
具有类型int
,并且该类型是从函数返回的,因此该函数的返回类型也是int
.
Defines a mutable variable initialised to 1, then assigns a new value (a + 1) to it using the <-
operator before returning the updated value on the last line. Since a
has type int
and this is returned from the function the return type of the function is also int
.
第一个例子
let count =
let mutable a = 1
fun () -> a <- a + 1; a
还声明了一个初始化为1的int
.但是,不是直接返回它,而是返回在a
上关闭的函数.每次调用此函数时,a都会递增,并返回更新的值.它可以等效地写为:
also declares an int
a initialised to 1. However instead of returning it directly it returns a function which closes over a
. Each time this function is called, a is incremented and the updated value returned. It could be equivalently written as:
let count =
let mutable a = 1
let update () =
a <- a + 1
a
update
fun () -> ...
defines a lambda expression. This version returns a 1-argument function reflected in the different return type of unit -> int
.
这篇关于无法理解函数体内F#可变变量的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!