F# string.Format

f#
25,654

Solution 1

If you want to avoid using the full name, you can use open in F#:

open System
let s = String.Format("Hello {0}", "world")

This should work in both F# interactive (enter the open clause first) and in normal compiled applications. The key thing is that you must write String with upper-case S. This is because string in C# isn't a usual type name - it is a keyword refering to the System.String type.

Alternatively, you could also take a look at the sprintf function. It is an F#-specific alternative to String.Format which has some nice benefits - for example it is type checked:

let s = sprintf "Hello %s! Number is %d" "world" 42

The compiler will check that the parameters (string and int) match the format specifiers (%s for string and %d for integers). The function also works better in scenarios where you want to use partial function application:

let nums = [ 1 .. 10 ]
let formatted = nums |> List.map (sprintf "number %d")

This will produce a list of strings containing "number 1", "number 2" etc... If you wanted to do this using String.Format, you'd have to explicitly write a lambda function.

Solution 2

the full name of it is:

System.String.Format
Share:
25,654
mamu
Author by

mamu

Updated on April 10, 2020

Comments

  • mamu
    mamu about 4 years

    I am writing my first F# library

    I am trying to use string.Format and it complains that no such function exists.

    Is it not available or am I doing something wrong?

  • mamu
    mamu almost 14 years
    I mean open System, C# stuffed everywhere :)
  • Jordan Gray
    Jordan Gray over 10 years
    I wish I could upvote this twice for suggesting sprintf, which is a better option most of the time.
  • Tomas Petricek
    Tomas Petricek over 10 years
    sprint is certainly more idiomatic, but it may be slower when called frequently in some loop...
  • Jordan Gray
    Jordan Gray over 10 years
    Wow—I'm surprised at just how slow sprintf is in F#. Good point.
  • Marc Sigrist
    Marc Sigrist over 10 years
    @Jordan: Starting with F# 3.1, sprintf runs up to 40x faster (see "Printf performance" here).
  • dudeNumber4
    dudeNumber4 over 7 years
    C# 6 string interpolation is so nice. It seems like it belongs in F#. Wish it were shared.
  • aloisdg
    aloisdg over 5 years
    @dudeNumber4 string interpolation is under discussion for F#. cf github.com/fsharp/fslang-design/blob/master/RFCs/…