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

僤鯓⒐⒋嵵緔 提交于 2019-12-04 16:25:06

问题


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

回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/1523500/how-do-i-create-an-extension-method-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!