Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an extension method (F#)? [duplicate]

How do I create an extension method in F#, for example, like this C# extension:

    public static string Right(this string host, int index)     {         return host.Substring(host.Length - index);     } 
like image 399
esac Avatar asked Oct 06 '09 03:10

esac


People also ask

How do you declare an extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

What is extension method with example?

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 extension method for a class?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.

What is extension method in C++?

An extension method allows you to add functionality to an existing type without modifying the original type or creating a derived type (and without needing to recompile the code containing the type that is extended.)


2 Answers

For an F# extension that can be called from F#:

type System.String with   member x.Right(index) = x.Substring(x.Length - index) 

Note that as of Beta 1, this doesn't result in a C#-compatible extension method.

For generating extension methods visible from C# (but not usable as extension methods in F#), see the link in Brian's edit to the original post.

like image 127
kvb Avatar answered Sep 28 '22 01:09

kvb


I know this doesn't really answer your question, but it is worth pointing out. In F# and other functional languages you often see modules with static methods (Like the Seq module) that are designed to be composed with other functions. As far as I've seen, instance methods aren't easily composed, which is one reason why these modules exist. In the case of this extension, you may want to add a function to the String module.

module String =     let right n (x:string) =         if x.Length <= 2 then x         else x.Substring(x.Length - n) 

It then would be used like so.

"test" |> String.right 2 // Resulting in "st"  ["test"; "test2"; "etc"] |> List.map (String.right 2) // Resulting in ["st"; "t2"; "tc"] 

Though in this case the extension method wouldn't be much more code.

["test"; "test2"; "etc"] |> List.map (fun x -> x.Right 2) 
like image 33
YotaXP Avatar answered Sep 28 '22 01:09

YotaXP