3

In C#, I do this:

 public const double PAPER_SIZE_WIDTH = 8.5 * 96; 

What is the best way to define this global constant in F#?

This fails:

  [<Literal>]
  let PaperSizeWidth = 8.5*96.0  

Error: This is not a valid constant expression

TIA

Alan Wayne
  • 5,122
  • 10
  • 52
  • 95
  • 1
    Defining `public const` is [bad practice](https://stackoverflow.com/a/756010/10339675) for libraries. You can precalculate value and write `let PaperSizeWidth = 816` and leave comment how you got this number. It will compile into static get-only property, which will be inlined by JIT during runtime. It you apply `[]` it will compile to `public const`, but as mentioned above - it's bad practice. – JL0PD Feb 07 '21 at 05:25
  • 1
    I have to disagree that this is bad practice. I also looked at the link, and what is described there is simply an example of a mistake that any sensible developer wouldn't do. – Bent Tranberg Feb 07 '21 at 07:15

1 Answers1

6

Arithmetic is not yet supported for numeric literals in F#. Instead, you have to provide the final value explicitly:

[<Literal>]
let PaperSizeWidth = 816.0

However, every value is immutable by default in F#, so this might be good enough, depending on your needs:

let PaperSizeWidth = 8.5 * 96.0
Brian Berns
  • 15,499
  • 2
  • 30
  • 40
  • 1
    This is not a good answer to the question, because the equivalent of using the const keyword in C# is indeed to use the [] attribute in F#. We call a literal a literal, and not a constant, otherwise confusion arises. – Bent Tranberg Feb 07 '21 at 07:19
  • 1
    Ok, I had forgotten that C# consts are evaluated at compile time. F# doesn’t support similar arithmetic in literals yet. See the link in my answer. – Brian Berns Feb 07 '21 at 07:22
  • 1
    Sorry, your answer is more informative than I thought at first. But I'd like to suggest you also add the alternative of calculating the expression and write let [] PaperSizeWidth = 816. – Bent Tranberg Feb 07 '21 at 07:26
  • I agree. I’ll update/clarify it tomorrow. – Brian Berns Feb 07 '21 at 07:27