Shorthand for calling a method on an object in F#

混江龙づ霸主 提交于 2019-12-07 22:22:16

问题


Is there a way to "generate" functions like this one:

fun x -> x.ToString

I would like to be able to turn an instance method into a static method which takes "this" as a parameter, like so:

items |> Seq.filter my_predicate |> Seq.map Object.ToString

回答1:


this has been discussed several times on the F# hub. See for example instance methods as functions. This is quite tricky problem, so there are no plans to have something like this in the first version of F# as far as I know, but it would be great to have something like that eventually :-).

Another workaround that you could do is to add static member as an extension method in F#:

type System.Object with
  static member ObjToString(o:obj) = o.ToString()

open System
[ 1 .. 10 ] |> Seq.map Object.ObjToString;;

But that is a bit ugly. Also, it seems that this works only if you use different name for the method. I guess that F# doesn't allow you to overload existing method with an extension method and always prefer the intrinsic one.




回答2:


I don't know if I exactly understood you, but for this specific example you could write:

items |> Seq.filter my_predicate |> Seq.map (fun x -> x.ToString)

or

let f = fun x -> x.ToString
items |> Seq.filter my_predicate |> Seq.map f


来源:https://stackoverflow.com/questions/677526/shorthand-for-calling-a-method-on-an-object-in-f

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