Saturday, December 24, 2011

F# Grouping Pattern



As the pattern matches contain more and more rules, you might want to combine patterns. There are two ways to combine patterns. First is to use OR represented by a
vertical pipe | , which combines patterns together so the rule will fire if any of the grouped patterns match. Second is to use AND represented by an ampersand &, which combines patterns together so that the rule will fire only if all of the grouped patterns match.

let vowelTest c =
match c with
|'a'|'e'|'i'|'o'|'u'
-> true
-> false
|_

let describeNumbers x y =
match x,y with
| 1, _
| _, 1
-> "One of the numbers is one."
| (2,_) & (_,2)
-> "Both of the numbers is two."
-> "Other."


AND pattern has litte use in normal pattern matching, however itz invaluable when using active patterns.

No comments:

Post a Comment