F# allows functions to be added as "members" to types when they are defined (for example, Record Types). However F# also allows new instance members to be added to existing types - even ones declared elsewhere and in other .net languages.
The following example adds a new instance method Duplicate
to all instances of String
.
type System.String with
member this.Duplicate times =
Array.init times (fun _ -> this)
Note: this
is an arbitrarily chosen variable name to use to refer to the instance of the type that is being extended - x
would work just as well, but would perhaps be less self-describing.
It can then be called in the following ways.
// F#-style call
let result1 = "Hi there!".Duplicate 3
// C#-style call
let result2 = "Hi there!".Duplicate(3)
// Both result in three "Hi there!" strings in an array
This functionality is very similar to Extension Methods in C#.
New properties can also be added to existing types in the same way. They will automatically become properties if the new member takes no arguments.
type System.String with
member this.WordCount =
' ' // Space character
|> Array.singleton
|> fun xs -> this.Split(xs, StringSplitOptions.RemoveEmptyEntries)
|> Array.length
let result = "This is an example".WordCount
// result is 4