32

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?

1 Answer 1

52

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
Sign up to request clarification or add additional context in comments.

1 Comment

See: Type Extensions (F#) and notice the difference between intrinsic extension and optional extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.