openlang

Formatting strings with F#

I'm building an F# library for the first time

Using string.Format gives me a complaint saying that the function doesn't exist.

Have I made a mistake, or is this unavailable?

The conversation continues 2

Follow the reasoning
  1. Permalink

    To skip spelling out the fully qualified name, F# lets you use open:

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

    That works in an ordinary compiled application as well as F# interactive (submit the open declaration beforehand). What's important here is spelling String with a capital S. The reson is that C#'s string isn't an ordinary name for a type - it's a keyword referring to System.String.

    Another option worth examining is sprintf. This F# alternative to String.Format offers useful advantages - one being that it is checked for correct types:

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

    The compiler verifies that the arguments (string and int) agree with their format markers (%s means string, while %d means integers). Partial function application is another situation in which this function fits more naturally:

    let values = [ 3 .. 12 ]
    let descriptions = values |> List.map (sprintf "number %d")

    The result is a list of strings holding "number 3", "number 4" and so on... Achieving the equivalent with String.Format would require writing out a lambda function.

Other sides of the same question

  1. Escaping percent characters when calling String.Format?

    My strings.xml file holds a SQL query, and I'm trying to construct the finished string in code with String.Format. The SELECT…

    Replies 3Latest activity java
  2. NAK only when the message has a degree sign (serial, Emacs)

    Basically, Temp: 23C gets an ACK but Temp: 23°C gets a NAK, and the board shows nothing. The log line is rx: "\25". Lowering…

    Replies 1Latest activity emacs-lisp
  3. Truncating by bytes like the old C++, and Rust panics

    Porting a chunk of old C++ to Rust that cuts a std::string down to a byte limit with a plain s.substr(0, n), and I figured it…

    Replies 4Latest activity rustcpp