F# Zen – The Literal Attribute

 

When pattern matching it is easy to forget that you are capturing a new value instead of matching against an existing one. Take this function for example:

 let E  = 2.718281828459
let PI = 3.141592653589

// Ooops - this captures a value
let isConstant x =
    match x with
    | PI
    | E -> true
    | _ -> false

The right way to write this code is to use the [<Literal>] attribute. This tells the F# compiler to treat this value as a constant literal which, among other things, enables it to be used with pattern matching.

 [<Literal>]
let E  = 2.718281828459
[<Literal>]
let PI = 3.141592653589

// This matches against the literal value
let isConstant x =
    match x with
    | PI
    | E -> true
    | _ -> false