[英]Extending F# List Module
I've been adding a few handy methods to some of the F# modules such as List. 我一直在为一些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
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.
我知道List是不可变的,那么如何向Ref类型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? 或者是否有某种方法来约束泛型只接受一个可变的?
Unfortunately, it doesn't appear to be possible to add extension members to closed constructed types (eg Ref<int>
or Seq<string>
). 不幸的是,似乎不可能将扩展成员添加到封闭的构造类型(例如
Ref<int>
或Seq<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 generic Ref<'T>
type. 这也适用于你想使用的代码,因为你替换更具体的类型
'a list
的泛型参数'T
的开放通用的Ref<'T>
类型。
Generic extension methods are now available in F# 3.1: 现在可以在F#3.1中使用通用扩展方法:
open System.Runtime.CompilerServices
[<Extension>]
type Utils () =
[<Extension>]
static member inline AppendMutate(ref: Ref<List<'a>>, elt) = ref := elt :: !ref
let ls = ref [1..10]
ls.AppendMutate(11)
printfn "%A" ls
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.