2009-10-01 16 views
7

Ho aggiunto alcuni metodi utili ad alcuni dei moduli F # come List.Estensione del modulo elenco 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 

e mi chiedo se è possibile aggiungere la mutazione? So che List è immutabile, quindi che ne dici di aggiungere un metodo mutabile a Ref of type List. Qualcosa come questo.

type Ref<'a when 'a :> Microsoft.FSharp.Collections.FSharpList<'a> > with //' 
    member this.AppendMutate element = 
     this := element :: !this 

o c'è qualche modo per vincolare un generico solo accettare un mutevole?

risposta

3

metodi di estensione generici sono ora disponibili 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 
3

Sfortunatamente, non sembra possibile aggiungere membri di interno a tipi chiusi chiusi (ad esempio Ref<int> o Seq<string>). Ciò vale anche per il codice che stai tentando di utilizzare, dal momento che stai sostituendo il tipo più specifico 'a list per il parametro generico 'T del tipo aperto generico Ref<'T>.

Problemi correlati