F# 4.5 introduces the match!
keyword which allows you to inline a call to another computation expression and pattern match on its result. Let’s have an example.
Here is the code I had to write before F# 4.5:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let doThingsAsync (url: string) = | |
async { | |
let! r = callServiceAsync url | |
match r with | |
| Some data -> printfn "Hello F#" | |
| None -> printfn "%s" s | |
} |
Notice that I have to bind the result of callServiceAsync before I can pattern match on it. Now let’s see how we can simplify this using the ‘match!’ keyword:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let doThingsAsync (url: string) = | |
async { | |
match! callServiceAsync url with | |
| Some data -> printfn "Hello F#" | |
| None -> printfn "%s" s | |
} |
When calling a computation expression with match!
, it will realize the result of the call like let!
. This is often used when calling a computation expression where the result is an optional.