Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment value in F#

Tags:

f#

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.

like image 576
cheziHoyzer Avatar asked Mar 04 '13 22:03

cheziHoyzer


2 Answers

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.

like image 163
Tomas Petricek Avatar answered Sep 19 '22 12:09

Tomas Petricek


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.

like image 28
Lee Avatar answered Sep 18 '22 12:09

Lee