Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does F# have its own string manipulation libraries?

Tags:

dll

f#

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" };;
like image 546
Scott Nimrod Avatar asked Feb 12 '16 16:02

Scott Nimrod


1 Answers

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.

like image 186
Guy Coder Avatar answered Nov 06 '22 22:11

Guy Coder