Why can't a function with byref be converted directly to delegate?

后端 未结 1 649
不知归路
不知归路 2021-01-13 00:10

Under normal circumstances, F# functions can be converted to delegates by calling new DelegateType and passing in the function as an argument. But when the dele

相关标签:
1条回答
  • 2021-01-13 00:57

    I think the problem is that byref<'T> is not an actual type in F# - it looks like a type (to make the language simpler), but it gets compiled to a parameter marked with the out flag. This means that byref<'T> can be only used in a place where the compiler can actually use the out flag.

    The problem with function values is that you can construct function e.g. by partial application:

    let foo (n:int) (b:byref<int>) = 
      b <- n
    

    When you pass foo as an argument to a delegate constructor, it is a specific case of partial application (with no arguments), but partial application actually needs to construct a new method and then give that to the delegate:

    type IntRefAction = delegate of byref<int> -> unit  
    
    let ac = IntRefAction(foo 5)
    

    The compiler could be clever and generate new method with byref parameter (or out flag) and then pass that by reference to the actual function, but in general, there will be other compiler-generated method when you don't use the fun ... -> ... syntax. Handling this would add complexity and I think that's a relatively rare case, so the F# compiler doesn't do that and asks you to be more explicit...

    0 讨论(0)
提交回复
热议问题