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

编程入门 行业动态 更新时间:2024-10-19 14:31:57
本文介绍了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>

我试图写其他函数 tryParse ,它使用静态方法 TryParse 并将解析结果包装到'一个选项类型中,以便更好地支持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 ,但这里有类型'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

我做错了什么?

推荐答案

strong> UPDATE

UPDATE

这似乎在F#3.0中已修复。

This appears to be fixed in F# 3.0.

answer:

我同意Stephen的评论,这很可能是一个错误。对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:37:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574104.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成员   参数   byref

发布评论

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

>www.elefans.com

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