【问题标题】:adding a property extension to lists, in F#在 F# 中向列表添加属性扩展
【发布时间】:2020-10-25 07:43:52
【问题描述】:

作为问题的后续:type extension on a list in F#

我想知道是否可以使用属性扩展列表

考虑代码:

let a = []
if a.IsEmpty then ...

但我也有共同点:

if not a.IsEmpty then

这不是超级可读的,所以我想我会做一个扩展(基于托马斯在上面问题中的回答):

[<Extension>]
type ListExtensions() =
    [<Extension>]
    static member IsNotEmpty(l: 'T list) = not l.IsEmpty

它允许我这样做:

if a.IsNotEmpty() then

但是我有:

if a.IsEmpty then // property
if a.IsNotEmpty() then // member

有没有办法进行属性扩展,使 IsNotEmpty 也是一个属性?

【问题讨论】:

  • 我认为没有!
  • 我也不认为有办法做到这一点。但是not a.IsEmpty 只比a.IsNotEmpty 长一个字符,而且它以not 开头的事实很明显它被否定了(阅读使用a.IsNotEmpty 的代码时可能很容易错过)
  • 我认为这有助于提高可读性,但与此同时,这主要是出于好奇:)
  • 我发现总是将 bool 命名为 bool 并返回肯定的东西,然后在需要时用 not 否定,这样会更容易混淆。
  • 我知道它不能回答你的问题,但对于这个特定的例子来说,它是惯用的 match list with | [] -&gt; ... | _ -&gt; ...

标签: types f# extension-methods


【解决方案1】:

这不是很有用吗?:

type List<'T> with
    member this.IsNotEmpty with get() = not this.IsEmpty

【讨论】:

    【解决方案2】:

    我认为我们应该使用类型增强:

    type List<'A> with
        member this.IsNotEmpty = this.IsEmpty |> not
    let a = []
    a.IsNotEmpty |> printfn "%b"
    

    这样,IsNotEmpty 是一个属性。

    【讨论】:

      猜你喜欢
      • 2013-10-10
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多