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.
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
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
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)
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.
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
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.
If you don't want to use mutable then you can't really do a destructive update like ++
is in C#. You could shadow a variable with a new one with the same name e.g.
let x = 4;
let x = x + 1 in (x+4) //returns 8
although you couldn't write this as a function.
EDIT: If do want to use mutable variables then you can create a function which modifies a ref:
let increment (ir: int ref) = ir := !ir + 1
You can then use it as
let i = ref 1
increment i
let iv = !i //iv contains 2
As Tomas points out in his answer, this function already exists and is called incr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With