F# 成员约束 + ^a byref 参数

编程入门 行业动态 更新时间:2024-10-19 12:47:14
本文介绍了F# 成员约束 + ^a byref 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在玩弄 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 参数

本文发布于:2023-11-10 02:38:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574105.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成员   参数   byref

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!