问题
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