Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

f#

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?

like image 225
Overlord Zurg Avatar asked Feb 10 '23 18:02

Overlord Zurg


1 Answers

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

like image 196
John Palmer Avatar answered Feb 16 '23 01:02

John Palmer