F# member constraints + ^a byref parameters

前端 未结 3 763
执念已碎
执念已碎 2020-12-17 21:03

After some playing around F# member constraints feature and writing function like this:

let inline parse< ^a when ^a : (static member Parse: string ->          


        
3条回答
  •  情深已故
    2020-12-17 21:51

    UPDATE

    This appears to be fixed in F# 3.0.

    Old answer:

    I agree with Stephen's comment that it's most likely a bug. There are many limitations on byref types, so it's not particularly surprising to me that they don't play well with member constraints. Here's an (ugly) workaround using reflection:

    type parseDel<'a> = delegate of string * 'a byref -> bool
    
    type Parser< ^a when ^a : (static member TryParse: string * ^a byref -> bool)> private ()=
      static let parser = System.Delegate.CreateDelegate(typeof>, typeof<'a>.GetMethod("TryParse", [|typeof; typeof<'a>.MakeByRefType()|])) :?> parseDel<'a>
      static member inline ParseDel = parser
    
    let inline tryParse (s:string) =
      let mutable x = Unchecked.defaultof< ^a>
      if Parser<_>.ParseDel.Invoke(s, &x) then
        Some x
      else None
    
    let one : int option = tryParse "1"
    

提交回复
热议问题