为什么 F# 的 printfn 可以处理文字字符串,但不能处理字符串类型的值? [英] Why does F#'s printfn work with literal strings, but not values of type string?

查看:18
本文介绍了为什么 F# 的 printfn 可以处理文字字符串,但不能处理字符串类型的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的 F# 代码中;我希望 printfn 被调用三次;每个都有一个字符串.但是,底线无法编译('string' 类型与'Printf.TextWriterFormat<'a>' 类型不兼容).

In the following F# code; I would expect that the printfn is being called three times; each with a string. However, the bottom line does not compile (The type 'string' is not compatible with the type 'Printf.TextWriterFormat<'a>').

前两行是什么意思表示这可以工作?它们不也是字符串吗?

What is it about the first two lines that means this can work? Aren't they just strings too?

open System

printfn ("
") // Works
printfn ("DANNY") // Works
printfn (DateTime.Now.ToLongTimeString()) // Doesn't compile

推荐答案

F# 编译器静态分析您传递给 printfn 的格式字符串,以检查您传递的参数对于您的格式说明符是否有效利用.例如,以下不能编译:

The F# compiler statically analyses the format strings you pass to printfn to check that the arguments you pass are valid for the format specifiers you use. For example, the following does not compile:

printfn "%d" "some value"

因为 string 与 %d 格式说明符不兼容.编译器将有效的格式字符串转换为 TextWriterFormat.

since string is not compatible with the %d format specifier. The compiler converts valid format strings into a TextWriterFormat<T>.

它不能对任意字符串执行此操作,并且由于它不执行转换,因此您会收到上面的类型错误.

It can't do this with arbitrary strings, and since it does not do the conversion, you get the type error above.

您可以使用 Printf.TextWriterFormat 自己进行转换.例如,对于需要 stringint 的格式字符串,您可以使用:

You can do the conversion yourself however using Printf.TextWriterFormat. For example, for a format string requiring a string and an int you can use:

let f = Printf.TextWriterFormat<string -> int -> unit>("The length of '%s' is: %d")
printfn f "something" 9

由于您的字符串没有格式占位符,您可以这样做:

Since your string has no format placeholders, you can do:

let f = Printf.TextWriterFormat<unit>(DateTime.Now.ToLongTimeString())
printfn f

这篇关于为什么 F# 的 printfn 可以处理文字字符串,但不能处理字符串类型的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆