F#中%A的含义是什么?

时间:2016-01-03 11:19:42

标签: f# string-formatting

在Microsoft Visual Studio 2015的F#教程中,这个代码虽然略有不同。

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

此代码返回标题The table of squares from 0 to 99 is: 然后它发送1-99及其方块的数字。我不明白为什么需要\n%A,特别是为什么它必须是A。

以下是其他一些不同字母的类似例子:

  1. 使用%d
  2. 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. 使用%s
    2. 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
      

      这让我有点困惑,因为他们必须有他们的信件或他们不会工作,所以可能有人。请解释%a%d%s以及其他任何其他\n的含义。

2 个答案:

答案 0 :(得分:3)

本页对此进行了解释:https://msdn.microsoft.com/en-us/library/ee370560.aspx

F#使用类似于C的合理标准格式字符串。

总结:

jQuery.each([1,2,3], function () {
    if(conditionMet) {
        return false;
    }
});

唯一奇怪的是%s prints a string %d is an integer 会尝试打印任何内容

%A只是换行符

答案 1 :(得分:0)

符号%A,%s和%d是占位符。当函数printfn由其参数值调用时,它们将被替换。每个占位符都需要特定的参数类型:

  • %s - 字符串
  • %d - signed int
  • %A - 漂亮的打印元组,记录和联合类型

以下是一些可以在F#REPL中执行的示例:

> printfn "a string: %s" "abc";;
a string: abc
val it : unit = ()

> printfn "a signed int: %d" -2;;
a signed int: -2
val it : unit = ()

> printfn "a list: %A" [1;2;3];;
a list: [1; 2; 3]
val it : unit = ()

> printfn "a list: %A" [(1, "a");(2, "b");(3, "c")];;
a list: [(1, "a"); (2, "b"); (3, "c")]
val it : unit = ()

> printfn "a signed int [%d] and a string [%s]" -2 "xyz";;
a signed int [-2] and a string [xyz]
val it : unit = ()

有关printfn及其占位符的更多信息,我建议使用此网站:

http://fsharpforfunandprofit.com/posts/printf/

字符串" \ n"与占位符没有直接关系。它插入一个新行。

相关问题