Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# string.Format

Tags:

f#

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?

like image 737
mamu Avatar asked Jun 05 '10 04:06

mamu


2 Answers

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.

like image 178
Tomas Petricek Avatar answered Nov 01 '22 22:11

Tomas Petricek


the full name of it is:

System.String.Format
like image 3
Yin Zhu Avatar answered Nov 01 '22 22:11

Yin Zhu