Feeding a function result into a pattern matching function in F#
June 3, 2017 Leave a comment
Say we have an F# function that returns a tuple of two elements:
let isGreaterThan x y = if x > y then (true, x - y) else (false, 0)
…, i.e. we return true and the difference between the two input integers if the first integer is greater. Otherwise we return a false and a 0. Here’s how we can consume this function:
let isGreaterThan x y = if x > y then (true, x - y) else (false, 0) let (gt, diff) = isGreaterThan 10 6 printfn "Is greater: %b, diff: %i" gt diff
…which prints “Is greater: true, diff: 4” in the interactive window. We can feed the result into a pattern matching expression and branch our logic as follows:
isGreaterThan 19 6 |> function | (true, diff) -> printfn "Difference: %i" diff | (false, diff) -> printfn "Less then"
The pattern matching expression is introduced by the function keyword followed by pattern matching logic. The above program prints “Difference: 13” in the interactive window.
The pattern matching branches must be exhaustive so the following would not be sufficient:
isGreaterThan 19 6 |> function | (true, diff) -> printfn "Difference: %i" diff
The code still runs but we get a warning: Incomplete pattern matches on this expression. For example, the value ‘(false,_)’ may indicate a case not covered by the pattern(s).
We get an exception in case there’s no matching pattern branch:
isGreaterThan 6 19 |> function | (true, diff) -> printfn "Difference: %i" diff
Microsoft.FSharp.Core.MatchFailureException: The match cases were incomplete
View all F# related articles here.