如果不想写完整限定名,F# 允许使用 open。
open System
let greeting = String.Format("Hello {0}", "world")
普通的编译应用和 F# interactive 都可以这样用(先输入 open 声明)。关键是 String 要用大写的 S。这是因为 C# 的 string 并不是普通类型名称,而是指向 System.String 的关键字。
另一个值得考虑的选择是 sprintf。这是 F# 对 String.Format 的替代方案,有一些实用优点,比如会检查类型。
let greeting = sprintf "Hello %s! Number is %d" "world" 56
编译器会检查参数(string 和 int)是否符合格式说明符(%s 表示字符串,%d 表示整数)。需要部分应用函数时,这个函数也更自然。
let values = [ 3 .. 12 ]
let descriptions = values |> List.map (sprintf "number %d")
结果是一个字符串列表,里面有 "number 3"、"number 4" 等内容……要用 String.Format 实现同样的效果,就得明确写出一个 lambda 函数。
从英语翻译·查看原文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.