Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the type of a first-class function contain byrefs?

Tags:

f#

For example, the following isn't allowed, and I'm not sure why:

> let f () = 
    let f2 (a : byref<int>) =
        ()
    let mutable a = 0
    f2 &a;;

My guess would be that the byref could be a mutable reference to a stack variable, which could go out of scope if f2 decides to store it somewhere. Or is it something else?

like image 779
Muhammad Faizan Avatar asked Jun 30 '16 17:06

Muhammad Faizan


2 Answers

The .NET type system does not allow byref types to be used as generic type arguments (e.g. you can't create a List<byref<int>>). Since (first class) F# functions are actually instances of the FSharpFunc<_,_> type, this means that F# functions also can't use byrefs in their domain or range.

like image 145
kvb Avatar answered Nov 04 '22 16:11

kvb


The error seems to stem from the fact that you are declaring f2 as a nested function. If you extract it from beneath f, it compiles:

let f2 (a : int byref) = ()

let f () =
    let mutable a = 1
    f2 &a
like image 43
dumetrulo Avatar answered Nov 04 '22 14:11

dumetrulo