Extending F# List Module

送分小仙女□ 提交于 2019-12-07 01:41:11

问题


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

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?


回答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



回答2:


Unfortunately, it doesn't appear to be possible to add extension members to closed constructed types (e.g. Ref<int> or Seq<string>). This also applies to the code you're trying to use, since you're substituting the more specific type 'a list for the generic parameter 'T of the open generic Ref<'T> type.



来源:https://stackoverflow.com/questions/1505656/extending-f-list-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!