Search code examples
f#string-formatting

What does %A mean in F#?


In the F# tutorial for Microsoft Visual Studio 2015 there was this code though slightly varied.

module Integers = 

    /// A list of the numbers from 0 to 99
    let sampleNumbers = [ 0 .. 99 ]

    /// A list of all tuples containing all the numbers from 0 to 99 andtheir squares
    let sampleTableOfSquares = [ for i in 0 .. 99 -> (i, i*i) ]

    // The next line prints a list that includes tuples, using %A for generic printing
    printfn "The table of squares from 0 to 99 is:\n%A" sampleTableOfSquares
    System.Console.ReadKey() |> ignore

This code returns the heading The table of squares from 0 to 99 is:.
Then it sends the numbers from 1-99 and their squares. I don't understand why \n%A is needed and specifically why it has to be an A.

Here are some other similar examples with different letters:

  1. Uses %d
module BasicFunctions = 

    // Use 'let' to define a function that accepts an integer argument and returns an integer. 
    let func1 x = x*x + 3             

    // Parenthesis are optional for function arguments
    let func1a (x) = x*x + 3             

    /// Apply the function, naming the function return result using 'let'. 
    /// The variable type is inferred from the function return type.
    let result1 = func1 4573
    printfn "The result of squaring the integer 4573 and adding 3 is %d" result1
  1. Uses %s
module StringManipulation = 

    let string1 = "Hello"
    let string2  = "world"

    /// Use @ to create a verbatim string literal
    let string3 = @"c:\Program Files\"

    /// Using a triple-quote string literal
    let string4 = """He said "hello world" after you did"""

    let helloWorld = string1 + " " + string2 // concatenate the two strings with a space in between
    printfn "%s" helloWorld

    /// A string formed by taking the first 7 characters of one of the result strings
    let substring = helloWorld.[0..6]
    printfn "%s" substring

This is making me a little confused because they have to have them letters or they won't work so could someone. Please explain the %a, %d and %s and any other if there are some and possibly what \n means as well.


Solution

  • This is all explained on this page: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/plaintext-formatting

    F# uses reasonably standard format strings similar to C.

    To summarise:

    %s prints a string
    %d is an integer
    

    the only weird one is %A which will try to print anything

    the \n is just a newline