9

在玩了一些 F# 成员约束功能和编写这样的函数之后:

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

这工作得很好:

let xs = [ "123"; "456"; "999" ] |> List.map parse<int>

我正在尝试编写其他 func tryParse,它使用静态方法TryParse并将解析结果包装成'a option类型,以便在 F# 中获得更好的支持。像这样的东西不会编译:

let inline tryParse s =
    let mutable x = Unchecked.defaultof< ^a>
    if (^a: (static member TryParse: string * ^a byref -> bool) (s, &x))
        then Some x else None

错误是:

错误 FS0001:此表达式的类型应为 byref<'a> 但此处的类型为 'a ref

F# ref-cells 也不起作用:

let inline tryParse s =
    let x = ref Unchecked.defaultof< ^a>
    if (^a: (static member TryParse: string * ^a byref -> bool) (s, x))
        then Some x else None

我究竟做错了什么?

4

3 回答 3

6

更新

这似乎在 F# 3.0 中得到修复。

老答案:

我同意斯蒂芬的评论,即这很可能是一个错误。byref 类型有很多限制,所以它们不能很好地处理成员约束对我来说并不奇怪。这是使用反射的(丑陋的)解决方法:

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<parseDel<'a>>, typeof<'a>.GetMethod("TryParse", [|typeof<string>; 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"
于 2011-01-11T14:44:28.130 回答
2

我认为这也是一个错误,具有成员约束和 byref 类型。我可以通过更改成员约束的签名来制作一个稍微不那么难看的反射版本:

let inline tryParse<'a when 'a : (static member TryParse : string -> 'a byref -> bool)>  s  =
    let args = [| s ; null |]
    if typeof<'a>
        .GetMethod("TryParse", [| typeof<string>; typeof< ^a>.MakeByRefType() |])
        .Invoke(null, args) = box true 
        then Some (args.[1] :?> 'a) 
        else None

这个非常接近:

let inline tryParse< ^a when ^a: (static member TryParse: string -> ^a byref -> bool)> s =
    let mutable x = Unchecked.defaultof<'a>
    if (^a: (static member TryParse: string -> ^a byref -> bool) (s, &x))
        then Some x else None

但我得到一个错误FS0421:当我尝试编译它时,此时不能使用变量“x”的地址。

于 2011-01-12T14:17:28.503 回答
2

这可以编译但仍然无法按预期工作:

let inline tryParse< ^a when ^a: (static member TryParse: string -> ^a ref -> bool) > s =
  let x = ref Unchecked.defaultof< ^a>
  match (^a: (static member TryParse: string -> ^a ref -> bool )  (s, x)) with
    | false -> None
    | true -> Some(!x)

// returns [Some 0; Some 0; Some 0; null], so our tryParse is not retrieving the value from the ref
let xs = [ "1"; "456"; "999"; "a" ] |> List.map tryParse<int>

在这种特定情况下,我不会使用反射,而是在 f# 中从 Parse 重新创建 TryParse

let inline tryParse< ^a when ^a: (static member Parse: string -> ^a) > s =
  try  
    Some(^a: (static member Parse: string -> ^a)  s)
  with
    | exn -> None

let xs = [ "1"; "456"; "999"; "a" ] |> List.map tryParse<int>
于 2011-02-05T08:53:43.060 回答