OCaml Printf.sprintf [英] OCaml Printf.sprintf

查看:123
本文介绍了OCaml Printf.sprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现这种现象?

Why does this behavior occur?

# Printf.sprintf ("Foo %d %s") 2 "bar";;
- : string = "Foo 2 bar"

# Printf.sprintf ("Foo %d" ^ " %s") 2 "bar";;
  Printf.sprintf ("Foo %d" ^ " %s") 2 "bar";;
Error: This expression has type string but an expression was expected of type
         ('a -> 'b -> 'c, unit, string) format =
           ('a -> 'b -> 'c, unit, string, string, string, string) format6

我希望首先评估字符串连接,所以一切都会正常进行.这是否与Printf所采用的类型系统诡计有关?

I would expect that the string concatenation would be evaluated first, so everything will proceed as normal. Does this have to do with the type system trickery that Printf employs?

推荐答案

是的,它与类型系统欺骗有关.如果要创建格式字符串,则需要使用(^^)运算符:

Yes, it has to do with type system trickery. If you want to create a format string you need to use the (^^) operator:

# Printf.sprintf ("Foo %d" ^^ " %s") 2 "bar";;
- : string = "Foo 2 bar"

我对这种技巧并没有太深的了解,但是我相信如果键入上下文需要,编译器愿意将字符串 constant 提升为printf格式.但是,("Foo %d" ^ " %s")的结果不是字符串常量,因此不会被提升. (^^)运算符创建一个键入上下文,如果两个操作数都是字符串常量,则可以提升它们.

I'm not deeply schooled in this trickery, but I believe that the compiler is willing to promote a string constant to a printf format if the typing context calls for it. However, the result of ("Foo %d" ^ " %s") is not a string constant, so it doesn't get promoted. The (^^) operator creates a typing context where both operands can be promoted if they are string constants.

您会看到为什么它必须是字符串常量:否则,将无法确定(要打印的值)关联的类型.

You can see why it would have to be a string constant: otherwise the associated types (of the values to be printed) can't be determined.

这篇关于OCaml Printf.sprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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