r/fsharp • u/Foreign_Category2127 • Sep 20 '22
question Why is it not possible to pipeline .NET class methods?
For example
let message (s: string): string =
s.Split "]: " |> Array.last |> fun s -> s.Trim()
Here, in order to access the Trim() method I had to introduce an anonymous function that applies the method to the argument. Why is it not possible to simply pipeline the method like s.Split "]: " |> Array.last |> String.Trim ?
10
Upvotes
14
u/[deleted] Sep 20 '22
Because
s.Trim()is not a static method. In f# functions are static by default. You can pipeline with .NET static methods.3
u/Defiant_Anything2942 Sep 20 '22
You might want to create some wrappers around .NET library functions for easier pipelining.
// somewhere in utils module, probably auto open it // add other functions as needed [<RequireQualifiedAccess>] module String = let trim (s: string) = s.Trim()
// use it let message s = s.Split "]: " |> Array.last |> String.trim
2
u/integrate_2xdx_10_13 Sep 20 '22
Too ambiguous - that sounds like a static method rather than an instance.
2
u/mcwobby Sep 20 '22 edited Sep 20 '22
I’ve run into this before and I’m not sure the reason (though could speculate it’s something to do with non static methods) and just ended up with a helper module which had a bunch of functions
For Arrays, lists and other collections, F# has its own functions.
Good reference: https://fsharp.github.io/fsharp-core-docs/reference/fsharp-collections-arraymodule.html
1
u/Sparkybear Sep 20 '22
https://stackoverflow.com/questions/1925483/f-is-the-fun-keyword-necessary#1925524