According to this post, F# supports extension methods on object instances and static classes. For example:
module CollectionExtensions = type System.Linq.Enumerable with static member RangeChar(first:char, last:char) = {first .. last} open ExtensionFSharp.CollectionExtensions
If I type System.Linq.Enumerable.
, the static method RangeChar
appears in my Intellisense window.
I want to add a static method, for_alli
, to the Seq module. I've modified the following code above as follows:
module SeqExtensions = type Microsoft.FSharp.Collections.Seq with (* error on this line *) static member for_alli f l = l |> Seq.mapi (fun i x -> i, x) |> Seq.for_all (fun (i, x) -> f i x)
Although both snippets of code have the same structure, SeqExtensions
doesn't compile. F# highlights the word Seq
and returns the error "The type 'Seq' is not defined".
How do I create static extension methods on Seq module?
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.
Extension methods are static because they get the instance passed in via the first parameter, and they don't act on the actual instance of their declaring class. Also, they're just a syntactic sugar. CLR doesn't support such a thing.
In Java you add extension methods via Manifold, a jar file you add to your project's classpath. Similar to C# a Java extension method is declared static in an @Extension class where the first argument has the same type as the extended class and is annotated with @This .
To extend an F# module, just create another module with the same name:
module Seq = let myMap f s = seq { for x in s do yield f x } Seq. // see your stuff here alongside normal stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With