扩展F#列表模块 [英] Extending F# List Module
本文介绍了扩展F#列表模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在一些F#模块(例如List)中添加了一些方便的方法.
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
我想知道是否可以添加突变?我知道List是不可变的,那么如何向List类型的Ref添加可变方法.像这样的东西.
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?
推荐答案
通用扩展方法现在在F#3.1中可用:
Generic extension methods are now available in 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
这篇关于扩展F#列表模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文