Does F# have its own string manipulation libraries?
As I am attempting to learn F#, I find myself using the existing System.string methods?
Should I be doing this?
Code:
open System
type PhoneNumber =
{ CountryCode:int
Number:string }
// b. Create a function formatPhone that accepts a PhoneNumber record and formats it to look like something like this: "+44 1234 456789"
let formatPhone phoneNumber =
let getLeadingCharacters (length:int) (text:string) =
text.Substring(0, length)
let getLastCharacters (length:int) (text:string) =
text.Substring(text.Length - length, length)
printf "+%i %s %s" phoneNumber.CountryCode
(phoneNumber.Number |> getLeadingCharacters 4)
(phoneNumber.Number |> getLastCharacters 6)
formatPhone { CountryCode=44; Number="123456789" };;
UPDATE
Updated function from:
let formatPhone phoneNumber =
let getLeadingCharacters (length:int) (text:string) =
text.Substring(0, length)
let getLastCharacters (length:int) (text:string) =
text.Substring(text.Length - length, length)
printf "+%i %s %s" phoneNumber.CountryCode
(phoneNumber.Number |> getLeadingCharacters 4)
(phoneNumber.Number |> getLastCharacters 6)
formatPhone { CountryCode=44; Number="123456789" };;
to:
let formatPhone phoneNumber =
printf "+%i %s %s" phoneNumber.CountryCode
phoneNumber.Number.[0..3]
phoneNumber.Number.[4..8]
formatPhone { CountryCode=44; Number="123456789" };;
No, F# does not have a specific String library that duplicates the .NET library. It does have a string module with extra string functions.
Yes, use the .NET functions.
The fact that F# can make use of all of the .NET library is one of it's strongest features. It does seem odd at first to mix functions using curried parameters with functions from .NET using tuple parameters.
That is why in NuGet you will see packages that also have the FSharp extension. e.g. MathNet Numerics and MathNet Numerics FSharp. These are wrapper functions that allow for idiomatic F# use of the .NET library.
When looking for functions and methods for use with F# I often use this trick.
To search .NET use class
as a keyword and to search for F# specific code use module
as keyword.
For example:
Google: MSDN string class
First item: String Class
Google: MSDN string module
First item: Core.String Module (F#) (This is now a 404) but it is also a valid link for F# Language Reference for String. Something is amiss.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With