gra*_*bot 7 extension-methods f# module 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
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以添加突变?我知道List是不可变的,那么如何向Ref类型List添加一个可变方法.像这样的东西.
type Ref<'a when 'a :> Microsoft.FSharp.Collections.FSharpList<'a> > with //'
member this.AppendMutate element =
this := element :: !this
Run Code Online (Sandbox Code Playgroud)
或者是否有某种方法来约束泛型只接受一个可变的?
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
Run Code Online (Sandbox Code Playgroud)