扩展 F# 列表模块

发布于 2024-08-06 04:39:17 字数 663 浏览 9 评论 0原文

我已经向一些 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 类型的 Ref 添加一个可变方法怎么样?像这样的东西。

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

或者有什么方法可以限制泛型只接受可变的?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我早已燃尽 2024-08-13 04:39:17

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

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
泡沫很甜 2024-08-13 04:39:17

不幸的是,似乎不可能将扩展成员添加到封闭构造类型(例如 RefSeq)。这也适用于您尝试使用的代码,因为您正在用更具体的类型 'a list 替换开放泛型 'T 的泛型参数 'T code>Ref<'T> 类型。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文