扩展 F# 列表模块
我已经向一些 F# 模块(例如 List)添加了一些方便的方法。
type Microsoft.FSharp.Collections.FSharpList<'a> with //'
static member iterWhile (f:'a -> bool) (ls:'a list) =
let rec iterLoop f ls =
match ls with
| head :: tail -> if f head then iterLoop f tail
| _ -> ()
iterLoop f ls
我想知道是否可以添加突变?我知道 List 是不可变的,那么向 List 类型的 Ref 添加一个可变方法怎么样?像这样的东西。
type Ref<'a when 'a :> Microsoft.FSharp.Collections.FSharpList<'a> > with //'
member this.AppendMutate element =
this := element :: !this
或者有什么方法可以限制泛型只接受可变的?
I've been adding a few handy methods to some of the F# modules such as List.
type Microsoft.FSharp.Collections.FSharpList<'a> with //'
static member iterWhile (f:'a -> bool) (ls:'a list) =
let rec iterLoop f ls =
match ls with
| head :: tail -> if f head then iterLoop f tail
| _ -> ()
iterLoop f ls
and i'm wondering if it's possible to add mutation? I know List is immutable so how about adding a mutable method to Ref of type List. Something like this.
type Ref<'a when 'a :> Microsoft.FSharp.Collections.FSharpList<'a> > with //'
member this.AppendMutate element =
this := element :: !this
or is there some way to constrain a generic to only accept a mutable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
F# 3.1 中现在提供了通用扩展方法:
Generic extension methods are now available in F# 3.1:
不幸的是,似乎不可能将扩展成员添加到封闭构造类型(例如
Ref
或Seq
)。这也适用于您尝试使用的代码,因为您正在用更具体的类型'a list
替换开放泛型'T
的泛型参数'T
code>Ref<'T> 类型。Unfortunately, it doesn't appear to be possible to add extension members to closed constructed types (e.g.
Ref<int>
orSeq<string>
). This also applies to the code you're trying to use, since you're substituting the more specific type'a list
for the generic parameter'T
of the open genericRef<'T>
type.