为什么 F# 的 printfn 可以处理文字字符串,但不能处理字符串类型的值?

编程入门 行业动态 更新时间:2024-10-09 22:16:21
本文介绍了为什么 F# 的 printfn 可以处理文字字符串,但不能处理字符串类型的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 自己进行转换.例如,对于需要 string 和 int 的格式字符串,您可以使用:

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 可以处理文字字符串,但不能处理字符串类型的值?

本文发布于:2023-11-24 14:23:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   类型   文字   printfn

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!