在 F# 中的列表上键入扩展名

type extension on a list in F#

假设我有一个类型:

let MyType =
    some info
    ...

但是,常用在列表中:MyType列表

所以我可以定义:

let MyTypeList =
    MyType list

有没有办法在 MyTypeList 上定义类型扩充?

我的实际案例是某些工作的 returns 类型结果,它是分批处理的,我有一些代码可以告诉我整个批次是否正常,是否部分正常,或者是否一切都错了。如果我可以为列表类型添加扩展,语法会更简单。

 let a : MyTypeList = ...

 if a.IsAllOk() then ...

但我找不到如何使用列表来制作它。

two different ways of definining type extensions in F#个。一种选择是通过 F# 类型扩充,另一种是(C# 兼容的)扩展方法。

扩展方法方法允许您为特定类型实例化定义扩展,例如 list<MyType>:

type MyType = { N : int }
type MyTypeList = int list

[<System.Runtime.CompilerServices.Extension()>]
type MyTypeListExtensions() = 
  [<System.Runtime.CompilerServices.Extension()>]
  static member AllOk(l:MyTypeList) = false

let foo (a:MyTypeList) = 
  a.AllOk()