2009-10-01 128 views
7

我一直在爲一些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 

還是有某種方法來約束泛型只接受可變嗎?

回答

3

通用擴展方法現在在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 
3

不幸的是,似乎不可能將擴展成員添加到封閉構造類型(例如Ref<int>Seq<string>)。這也適用於您嘗試使用的代碼,因爲您將'a list更具體的類型替換爲開放式通用Ref<'T>類型的通用參數'T