The as pattern

Interestingly, a pattern case may have the as clause appended to it. This clause binds the matched value to a name that may be used within the corresponding result-expression of the match construction or elsewhere within a local context of an outer let binding. The following script demonstrates how flexible the as pattern can be (Ch4_3.fsx):

let verifyGuid g = 
  match System.Guid.TryParse g with 
  | (true,_ as r) -> sprintf "%s is a genuine GUID %A" g (snd r) 
  | (_,_ as r) -> sprintf "%s is a garbage GUID, defaults to %A" 
                        g (snd r);; 

In the first case, r is bound using as to the result of TryParse, which is the tuple, so the expression snd r yields the parsed GUID value.

In the second case, as bounds r to any tuple; however, it must be obvious from the match cases sequencing that this case matches the failed GUID parsing and the value of argument is a garbage.

The following screenshot reflects firing each of these using as binding match cases in FSI:

The as pattern

Pattern matching with as binding

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

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