扩展F#列表模块
问题描述:
我一直在为一些F#模块添加一些方便的方法,例如List。扩展F#列表模块
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
我想知道是否可以添加突变?我知道列表是不可变的,所以如何添加一个可变的方法给Ref类型List。像这样的东西。
type Ref<'a when 'a :> Microsoft.FSharp.Collections.FSharpList<'a> > with //'
member this.AppendMutate element =
this := element :: !this
还是有某种方法来约束泛型只接受可变吗?
答
通用扩展方法现在在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
答
不幸的是,似乎不可能将扩展成员添加到封闭构造类型(例如Ref<int>
或Seq<string>
)。这也适用于您尝试使用的代码,因为您将'a list
更具体的类型替换为开放式通用Ref<'T>
类型的通用参数'T
。