Matching literals

One of the simplest cases of matching patterns is a pattern represented by a literal and assuming a simple comparison-expression value equality. Literals can be of any numeric, character, or string types. They can also be cases of a .NET enumeration (each such case is inherently a symbolic name alias of the integer value) or a value decorated with the [<Literal>] attribute.

In the following script, I can easily match int literals and the int value aliased as THREE, decorated with the [<Literal>] attribute (Ch4_1.fsx):

[<Literal>] 
let THREE = 3 
 
let transformA v = 
  match v with 
  | 1 ->"1" 
  | 2 ->"2" 
  | THREE ->"3" 
 
transformA <| (1 + 2) 

This yields string "3", as expected. However, it wouldn't be possible to mix int literals with named int constant values from the following script (Ch4_1.fsx):

type Multiples = 
  | Zero = 0 
  | Five = 5 
 
let transformB ``compare me`` = 
  match ``compare me`` with 
  | Multiples.Zero ->"0" 
  | Multiples.Five ->"5" 
Multiples.Five |> transformB 

This yields string "5", although being literals, Multiples.Zero and Multiples.Five are typed as members of the Multiples enumeration.

(Besides, if you did not grok this yet, placing almost any text between the doubled backticks, such as ``compare me`` above, makes this text a valid F# name and, when used in moderation, may add to improved code readability).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset