简体   繁体   中英

F# Literal/constant can be composed with strings, but not int?

Why is this OK:

let [<Literal>] hi = "hi"
let [<Literal>] bye = "bye"
let [<Literal>] shortMeeting = hi + bye

...but this is not?

let [<Literal>] me = 1
let [<Literal>] you = 1
let [<Literal>] we = me + you

The third line gives the error:

This is not a valid constant expression

What's up with that?

So the spec / docs are a little unclear, but provide hints.

From the spec (for 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

This seems to suggest that even the combination of strings isn't allowed.

The documentation states that this changed in 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:

Note that integer addition is not on that list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM