Search code examples
functionf#intmutablebyref

F#: How to Call a function with Argument Byref Int


I have this code:

let sumfunc(n: int byref) =
  let mutable s = 0 
  while n >= 1 do
    s <- n + (n-1)
    n <- n-1
  printfn "%i" s

sumfunc 6

I get the error:

(8,10): error FS0001: This expression was expected to have type
    'byref<int>'
but here has type
    'int'

So from that I can tell what the problem is but I just dont know how to solve it. I guess I need to specify the number 6 to be a byref<int> somehow. I just dont know how. My main goal here is to make n or the function argument mutable so I can change and use its value inside the function.


Solution

  • This is such a bad idea:

    let  mutable n = 7
    let sumfunc2 (n: int byref)  =
        let mutable s = 0
        while n >=  1 do
            s <- n + (n - 1)
            n <- n-1
            printfn "%i" s
    
    sumfunc2 (&n)
    

    Totally agree with munn's comments, here's another way to implode:

    let sumfunc3 (n: int)  =
        let mutable s = n
        while s >=  1 do
            let n =  s + (s - 1)
            s  <- (s-1)
            printfn "%i" n
    
    sumfunc3 7