F# 打印函数
最后修改时间 2025 年 5 月 1 日
在本文中,我们将介绍 F# 语言中的打印函数。
在 F# 中,我们可以使用内置的 Console.WriteLine
函数打印到终端,或者使用 F# 特有的辅助函数 printf
和 printfn
。
Console.WriteLine
Console.WriteLine
是 .NET 中打印到标准输出的核心函数。
main.fsx
open System let name = "John Doe" let occupation = "gardener" Console.WriteLine($"{name} is a {occupation}")
在示例中,我们使用 Console.WriteLine
打印一条消息。该函数在 System
命名空间中可用。
Console.WriteLine($"{name} is a {occupation}")
我们使用字符串插值来构建消息。
$ dotnet fsi main.fsx John Doe is a gardener
printf 函数
printf
函数使用给定的格式打印到标准输出。
main.fsx
let name = "John Doe" let occupation = "gardener" printf "%s is a %s\n" name occupation
该示例使用 printf
向控制台打印一条消息。
printf "%s is a %s\n" name occupation
该函数将其第一个参数作为格式字符串。在格式字符串中,我们定义占位符,这些占位符将被后续参数的值替换。%s
特殊占位符将被字符串值替换。
printfn 函数
printfn
函数使用给定的格式打印到标准输出,并添加一个换行符。
main.fsx
printfn "The bool is %b" (5 > 0) printfn "Binary is %B" 123 printfn "The char is %c" 'F' printfn "The string is %s" "falcon or \"falcon\" " printfn "The int is %i" -3 printfn "The int is %d" 42 printfn "The float is %f" 42.0 printfn "The HEX is %X" 42 printfn "The float is %e" 0.0000042
我们使用 printfn
将值打印到终端。我们展示了各种格式说明符。
$ dotnet fsi main.fsx The bool is true Binary is 1111011 The char is F The string is falcon or "falcon" The int is -3 The int is 42 The float is 42.000000 The HEX is 2A The float is 4.200000e-006
sprintf 函数
sprintf
函数不打印到控制台。它构建一条消息(“打印”到变量)。
main.fsx
let name = "John Doe" let occupation = "gardener" let msg = sprintf "%s is a %s" name occupation printfn "%s" msg
该示例使用 sprintf
格式化一条消息,并使用 printfn
将其打印到控制台。
$ dotnet fsi main.fsx John Doe is a gardener
在本文中,我们已经学习了 F# 中的打印函数。