views:

135

answers:

2

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);
    }

EDIT

Basically a duplicate:

http://stackoverflow.com/questions/702256/f-extensions-in-c

(Asks a more in-depth question, but also answers this question)

+2  A: 

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.

kvb
darn, that's what I wanted.
esac
A: 

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)
YotaXP