C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
testPrint 0
testPrint 1
testPrint 2
testPrint 3
Output
Low number: 0
Low number: 1
Low number: 2
Other number: 3
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)
Output
true
false
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
Output
"cat"
"cat"
"dog"
"unknown"