F#中的增量值 [英] Increment value in F#
问题描述
也许这太简单了,但是我在网上找不到任何答案
我尝试在F#中增加值(如C#中的count++
).
我不想使用可变"选项,
我只想看一个例子,F#中的Increment函数应该是什么样子.
以及如何使用它.
Maybe it's too simple thing to do, but I can't find any answer in the web
I'm try to Increment value in F# (like count++
in C#).
I don't want to use "mutable" option,
I'm just want to see an example, who Increment function in F# should look like.
And how do I use it.
推荐答案
与C ++相同,递增值"的想法只有在使用可变值或使用变量时才有意义.可变参考单元格(本质上是一个存储可变值的简单对象).如果参考单元可变,则可以使用incr
函数:
The idea of "incrementing a value" in the same sense as in C++ only makes sense when you're working with mutable values or when you're using a mutable reference cell (essentially a simple object that stores a mutable value). If you have a mutable reference cell, you can use incr
function:
let count = ref 0
incr count
如果使用可变变量,则没有内置函数,您需要编写count + 1
:
If you use a mutable variable, then there is no built-in function for this and you need to write count + 1
:
let mutable count = 0
count <- count + 1
如果您使用不可变的值编写代码,则通常只需编写count + 1
,然后将结果传递给某个函数(或其他函数,具体取决于具体情况).例如,要计算F#列表的长度,应编写:
If you're writing code using immutable values, then you will generally just write count + 1
and then pass the result to some function (or somewhere else - this depends on the specific case). For example, to calculate the length of an F# list, you would write:
let rec length list =
match list with
| [] -> 0
| _::tail -> 1 + (length tail)
在此示例中,表达式1 + (...)
是C ++代码中与i++
相对应的代码,该代码在列表上进行迭代并计算其长度.表达式的结果未分配给新变量,因为它是length
函数的结果直接返回.
In this example, the expression 1 + (...)
is the code corresponding to i++
in a C++ code that iterates over a list and computes its length. The result of the expression is not assigned to a new variable, because it is returned directly as a result of the length
function.
编辑函数的参数是不可变的,这意味着您无法更改其值.正如Lee所提到的,您可以使用变量阴影来用新值隐藏旧值-但请注意,这仅具有局部效果(就像定义一个具有不同名称的新变量来存储新值).例如:
EDIT Parameters of functions are immutable meaning that you cannot change their values. As mentioned by Lee, you can use variable shadowing to hide the old value with a new one - but note that this only has a local effect (it is like defining a new variable with different name to store the new value). For example:
let rec length list count =
match list with
| [] -> count
| _::tail ->
let count = count + 1 // Variable shadowing used here
length tail count
您无法编写函数来简化let count = count + 1
行,如上所述,这等效于编写let newCount = count + 1
然后在最后一行使用newCount
.
You cannot write a function to simplify the line let count = count + 1
and as mentioned above, this is equivalent to writing let newCount = count + 1
and then using newCount
on the last line.
这篇关于F#中的增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!