Match
A program's job is the direct the flow of control. It tests values and takes actions. With pattern matching and match, this process is clarified.
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.
printfn
call. All other values reach the second.// 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 3Low number: 0 Low number: 1 Low number: 2 Other number: 3
List
matchingA 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.
oneOrTwoElements
function will return false.// 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)true false
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.
// 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"cat" "cat" "dog" "unknown"
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.
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.