F# Match KeywordTest data, and direct the flow of control, with the match keyword. Match inside a method.
Match. A program's job is the direct the flow of control. It tests values. It takes actions. With pattern matching and match, this process is clarified.
Pattern matching. The keyword match implements pattern matching. This is like a switch-statement. We often place match within a function.
This program shows a simple function called testPrint. One argument (v) is received by testPrint. A match construct is used.
With: This begins the body of the match. After with, we have the cases following vertical bars.
Logic: In this match example, the values 0, 1 and 2 reach the first printfn call. All other values reach the second.
F# program that uses match
// Create a method that receives one argument.
// ... Match the argument.
// If 0, 1 or 2, print Low number.
// In all other cases, print Other number.
let testPrint v =
match v with
| 0 | 1 | 2 -> printfn "Low number: %A" v
| _ -> printfn "Other number: %A" v
// Test our method.
Low number: 0
Low number: 1
Low number: 2
Other number: 3
A match can handle lists. We can match lists with a certain number of elements by introducing list patterns. Here we return true if a list has one or two elements.List
And: If a list is empty or has more than 2 elements, the oneOrTwoElements function will return false.
F# program that uses pattern matching on list
// Return true if one or two elements are present in the list.
let oneOrTwoElements list =
match list with
| [a] -> true
| [a; b] -> true
| _ -> false
// This list has two elements, so oneOrTwoElements returns true.
let names1 = ["cat"; "bird"]
printfn "%A" (oneOrTwoElements names1)
// Not one or two elements, so false.
let names2 = ["fish"; "monkey"; "human"]
printfn "%A" (oneOrTwoElements names2)
This kind of function contains a match construct but does not use the "match" keyword. We use the "function" keyword to specify a pattern-matching function.
Arguments: The arguments to the function are matched directly in the parts of the function. So we call "v" 1 to get "cat."
F# program that uses pattern-matching function
// A pattern-matching function.
// ... No match keyword is required.
// ... The argument is directly matched.
let v = function
| 1 | 2 -> "cat"
| 3 -> "dog"
| _ -> "unknown"
// Test the function.
let result1 = v 1
printfn "%A" result1
let result2 = v 2
printfn "%A" result2
let result3 = v 3
printfn "%A" result3
let result4 = v 4
printfn "%A" result4
Matching syntax at first looks strange. But it provides visual clarity and can be understood easily with some practice. The vertical bars begin cases in the match.
A review. F# allows many constructs that influence control flow. An if-statement can be used. But match, like a switch, is elegant and has clear syntax in this language.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.