Constants in F#

Our program will demonstrate the use of constants with character, string, boolean, and numeric values. Here’s the full source code.

open System

// Declares a string constant
let s = "constant"

[<EntryPoint>]
let main argv =
    printfn "%s" s
    
    // Declares a numeric constant
    let n = 500000000

    // Performs arbitrary precision arithmetic
    let d = 3e20 / float n
    printfn "%f" d

    // Explicit conversion to int64
    printfn "%d" (int64 d)

    // Using the constant in a context that requires it to have a type
    printfn "%f" (Math.Sin(float n))

    0 // return an integer exit code

To run the program, save the code in a file with the .fsx extension and use fsharpi to interpret it, or compile and run it using fsharpc and mono.

Using F# Interactive (fsharpi)

$ fsharpi constants.fsx
constant
600000000000.000000
600000000000
-0.28470407323754405

Compiling and Running with fsharpc and mono

$ fsharpc constants.fsx -o constants.exe
$ mono constants.exe
constant
600000000000.000000
600000000000
-0.28470407323754405

Now that we can run and build basic F# programs, let’s learn more about the language.