2009-10-01 4 views
7

List와 같은 F # 모듈에 몇 가지 편리한 메소드를 추가했습니다.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 

내가 돌연변이를 추가 할 수 있는지 궁금한가요? List가 불변이므로 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을 일반 매개 변수 'T 일반형 Ref<'T> 유형으로 대체하기 때문입니다.