Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concat in FSharp.Core.String vs Concat in System.String

Tags:

string

f#

I noticed that there is a lowercase String.concat in Microsoft.FSharp.Core and an uppercase System.String.Concat with several overloads. Intellisense picks one or the other if I type String.c or System.String.C

Are the String.xyz functions in Microsoft.FSharp.Core preferable to System.String.Xyz functions or the other way around? What are each type of function advantages and disadvantages?

In general, what are the advantages and disadvantages of using functions in FSharp.Core?

like image 923
Soldalma Avatar asked Aug 03 '26 22:08

Soldalma


1 Answers

I'm not sure that these 2 are equivalent:

FSharp's String.concat is used to join a sequence of strings into a single string with a delimeter:

let strings = [ "tomatoes"; "bananas"; "apples" ]
let fullString = String.concat ", " strings
printfn "%s" fullString

System.String.Concat is used to concatenate 2 (or more) separate strings together.

System.String.Join is the same as FSharp's String.concat - it's just a wrapper for it actually:

[<CompiledName("Concat")>]
let concat sep (strings : seq<string>) =  
    String.Join(sep, strings)

When writing F# you will find it more idiomatic to call F# functions over the ones from other .NET assemblies. You can partially apply F# functions for example, you can't to that with .NET method calls.

e.g. a function that always concats with a space can be defined like so:

let concatWithSpace xs = 
  String.concat " " xs

Which becomes more useful if you model it as part of your Domain, e.g. instead of concatWithSpace, it could be called formatReportElements or something with meaning.

like image 194
DaveShaw Avatar answered Aug 06 '26 12:08

DaveShaw