在玩弄 F# 成员约束功能并编写如下函数后:
After some playing around F# member constraints feature and writing function like this:
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#.这样的东西不能编译:
I'm trying to write other func tryParse, that uses static method TryParse and wraps the parse result into 'a option type for better support in F#. Something like this doesn't compiles:
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 但这里有类型'参考
error FS0001: This expression was expected to have type byref<'a> but here has type 'a ref
F# ref-cells 也不起作用:
F# ref-cells doesn't work too:
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我做错了什么?
推荐答案UPDATE
这似乎已在 F# 3.0 中修复.
This appears to be fixed in F# 3.0.
旧答案:
我同意斯蒂芬的评论,即这很可能是一个错误.byref 类型有很多限制,因此它们不能很好地处理成员约束对我来说并不特别令人惊讶.这是使用反射的(丑陋的)解决方法:
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<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"更多推荐
F# 成员约束 + ^a byref 参数
发布评论