Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static extension methods on Seq module

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?

like image 914
Juliet Avatar asked Mar 22 '09 18:03

Juliet


People also ask

Can extension methods be static?

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.

What is the difference between a static method and an extension method?

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.

Why Extension methods are static?

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.

Does Java have extension methods?

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 .


1 Answers

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 
like image 74
Brian Avatar answered Oct 01 '22 20:10

Brian