type extension on a list in F#

佐手、 提交于 2020-12-13 03:34:19

问题


Let's say I have a type:

let MyType =
    some info
    ...

but, it is commonly used in a list: MyType list

so I can define:

let MyTypeList =
    MyType list

is there a way to define a type augmentation on MyTypeList?

my practical case is that the type returns results of some work, it is handled in batches and I have some code that tell me if the whole batch is ok, if it is partially ok, or if everything went wrong. If I could add extensions to the list type, the syntax would be simpler.

 let a : MyTypeList = ...

 if a.IsAllOk() then ...

but I can't find how to make this with a list.


回答1:


There are two different ways of definining type extensions in F#. One option is via an F# type augmentation and the other is (C#-compatible) extension method.

The extension method approach lets you define extensions for a specific type instantiation, including for example 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()


来源:https://stackoverflow.com/questions/62703688/type-extension-on-a-list-in-f

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