Reputation: 908
I'm new to F#. I'm using VS2008 shell and F# interactive. I try to split a string using "System.String.Split" but then I get the error: "Split is not a static method"
code example:
let Count text =
let words = System.String.Split [' '] text
let nWords = words.Length
(nWords)
How do I use the String methods like split in F# ?
Upvotes: 51
Views: 42231
Reputation: 8556
Others have commented already that String.Split
is a method, not a static function.
However, as I mentioned in this other answer here, they recently introduce a new syntax in f#8 for cases like this, so we don't have to write those small and convenient module functions wrapping object members.
It is called _.Property
as a shorthand for (fun x -> x.Property)
, and can be done like this:
let count (text : string) =
text
|> _.Split(' ')
|> Seq.length
There is a limitation though: you can only use this new syntax to replace a lambda that does only an atomic expression, i.e.:
An atomic expression is an expression which has no whitespace unless enclosed in method call parentheses.
That is why, for example, I had to write it like _.Split(' ')
, as it is atomic. It would have not worked as _.Split ' '
(notice the whitespace before the curried parameter).
Upvotes: 1
Reputation: 37045
Using .NET member functions:
let count (text : string) =
text.Split [|' '|]
|> Seq.length
Or using FSharpx
, which gives us more ergonomic free-functions...
paket.dependencies
source https://api.nuget.org/v3/index.json
nuget FSharpx.Extras 2.3.2
paket.references
FSharpx.Extras
Usage:
open FSharpx
let count (text : string) =
text
|> String.splitChar [| ' ' |]
|> Seq.length
Note that F# Power Pack seems to be deprecated.
Upvotes: 1
Reputation: 69
The function String.split is now defined in the F# Power Pack. You must add
#r "FSharp.PowerPack.dll";;
#r "FSharp.PowerPack.Compatibility.dll";;
See the errata for Expert F#: http://www.expert-fsharp.com/Updates/Expert-FSharp-Errata-Jan-27-2009.pdf
Get FSharp.PowerPack.dll here: http://fsharppowerpack.codeplex.com/
Upvotes: 6
Reputation: 74802
You call them as instance methods:
let Count (text : string) =
let words = text.Split [|' '|]
let nWords = words.Length
(nWords)
(Note you need to use [| |]
because Split takes an array not a list; or, as per Joel Mueller's comment, because Split takes a params array, you can just pass in the delimiters as separate arguments (e.g. text.Split(' ', '\n')
).)
Upvotes: 62