type extension on a list in F#

Viewed 113

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 Answers

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()
Related