Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# mutable function arguments

Tags:

f#

Is there a way to have mutable function arguments in F#, that would allow something like

let mutable i = 9

let somefun n = n <- 12; ()

somefun i

(* *not* a real-world example *)

I do understand that this can be made to work by wrapping it into a record type

type SomeRec = { mutable i: int }

let ri = { i = 9 }

let someotherfun r = r.i <- 12; ()

and that this can be done in a similar fashion for class members. However, even after browsing through the whole F# Language Specification (yes, I did!), there seems to be no syntax to allow the first case, and the compiler appears to be quite unhappy about my trying this. I was hoping there would be some sort of type annotation, but mutable cannot be used in such.

I also know that I should not be doing this sort of thing in the first place, but the first case (int binding) and the second (record type) are semantically identical, and any such objection would hold for both cases equally.

So I think that I am missing something here.

like image 759
Alexander Rautenberg Avatar asked Sep 23 '10 13:09

Alexander Rautenberg


2 Answers

You can use ref as arguments

let v = ref 0
let mutate r = 
    r := 100
mutate v
printfn "%d" !v

Or byref keyword

let mutable v = 0
let mutate (r : byref<_>) = 
    r <- 100
mutate &v
printfn "%d" v
like image 168
desco Avatar answered Oct 12 '22 23:10

desco


Use byref keyword which is equivalent to C# ref. See Passing by reference.

like image 28
Artem Koshelev Avatar answered Oct 13 '22 00:10

Artem Koshelev