Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the F# string concatenation operator ^

Tags:

.net

f#

I was reading through the docs and hit this paragraph

There are two ways to concatenate strings: by using the + operator or by using the ^ operator. The + operator maintains compatibility with the .NET Framework string handling features.

I bashed it into my linqpad, and it runs ok, but I do get a warning

This construct is for ML compatibility. Consider using the '+' operator instead

Had a search around the web for further detail but came up with nix.

Can anyone elaborate on the ^'s intended function ?

like image 461
OrdinaryOrange Avatar asked Jun 08 '19 12:06

OrdinaryOrange


1 Answers

Short answer - use + rather than ^ like the warning suggests, the operators are interchangeable.

The longer answer: looking into FSharp.Core, you will find that both of those operators are inlined and defer to System.String.Concat.

See here for ^:

let inline (^)     (x:string) (y:string) = System.String.Concat(x,y)

and here for +:

let inline (+) (x: ^T) (y: ^U) : ^V = 
    AdditionDynamic<(^T),(^U),(^V)>  x y 
    ...
    when ^T : string      and ^U : string     = 
       (# "" (System.String.Concat((# "" x : string #),(# "" y : string #))) : ^T #)

with the + definition being more complicated, but boiling down to the same thing.

^ seems to be one of many (and in practice obsolete) constructs in F# that were adopted from OCaml at a time when ease of porting OCaml code to F# was considered an important selling point for the language:

value prefix ^ : string -> string -> string
s1 ^ s2 returns a fresh string containing the concatenation of the strings s1 and s2.

I can't really remember ever seeing code using ^ in practice, and wouldn't be able to tell F# had this operator if you asked me.

like image 83
scrwtp Avatar answered Oct 11 '22 13:10

scrwtp