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 ...

Get F# 4.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.