F# Literal/constant 可以用字符串组合,不能用int?
F# Literal/constant can be composed with strings, but not int?
为什么这样可以:
let [<Literal>] hi = "hi"
let [<Literal>] bye = "bye"
let [<Literal>] shortMeeting = hi + bye
...但这不是吗?
let [<Literal>] me = 1
let [<Literal>] you = 1
let [<Literal>] we = me + you
第三行报错:
This is not a valid constant expression
这是怎么回事?
所以规范/文档有点不清楚,但提供提示。
来自规范(针对 F# 3.0):
A value that has the Literal attribute is subject to the following
restrictions:
It may not be marked mutable or inline. It may not also have the
ThreadStaticor ContextStatic attributes. The righthand side expression
must be a literal constant expression that is made up of either:
A simple constant expression, with the exception of (), native integer
literals, unsigned native integer literals, byte array literals,
BigInteger literals, and user-defined numeric literals.
OR
A reference to another literal
这似乎表明即使是字符串组合也是不允许的。
文档指出这在 F# 3.1 中发生了变化:
https://msdn.microsoft.com/en-us/library/dd233193.aspx
As of F# 3.1, you can use the + sign to combine string literals. You
can also use the bitwise or (|||) operator to combine enum flags. For
example, the following code is legal in F# 3.1:
请注意,整数加法不在该列表中
为什么这样可以:
let [<Literal>] hi = "hi"
let [<Literal>] bye = "bye"
let [<Literal>] shortMeeting = hi + bye
...但这不是吗?
let [<Literal>] me = 1
let [<Literal>] you = 1
let [<Literal>] we = me + you
第三行报错:
This is not a valid constant expression
这是怎么回事?
所以规范/文档有点不清楚,但提供提示。
来自规范(针对 F# 3.0):
A value that has the Literal attribute is subject to the following restrictions:
It may not be marked mutable or inline. It may not also have the ThreadStaticor ContextStatic attributes. The righthand side expression must be a literal constant expression that is made up of either:
A simple constant expression, with the exception of (), native integer literals, unsigned native integer literals, byte array literals, BigInteger literals, and user-defined numeric literals.
OR
A reference to another literal
这似乎表明即使是字符串组合也是不允许的。
文档指出这在 F# 3.1 中发生了变化:
https://msdn.microsoft.com/en-us/library/dd233193.aspx
As of F# 3.1, you can use the + sign to combine string literals. You can also use the bitwise or (|||) operator to combine enum flags. For example, the following code is legal in F# 3.1:
请注意,整数加法不在该列表中