Thomas
Thomas

Reputation: 12107

How can I write += operation with mutables in F#

with the simple case of, in C#:

i += 1;

how can I write this with a mutable in F#, other than:

i <- i + 1

is there a shorter syntax?

Upvotes: 0

Views: 317

Answers (2)

Nghia Bui
Nghia Bui

Reputation: 3784

No, F# and Functional Programming in general discourage mutability. Thus the language doesn't make writing mutable code convenient.

If you love += you can create that operator by yourself:

let inline (+=) a b = a := !a + b
// test
let a = ref 100
a += 2
printfn "%d" !a // 102

You can check this article for more information about the Ref type.

Upvotes: 6

AFAIK there's no built-in operator for increment mutables in place but there's a built-in function to increment int ref values.

let x = ref 0
incr x
printfn "%A" !x  // ! dereferences an int ref

Upvotes: 2

Related Questions