Last active
April 8, 2021 20:08
-
-
Save ninjarobot/a0f8792a1089a6df2fd0f42c5ad22746 to your computer and use it in GitHub Desktop.
Using partial active patterns to return calculated data in pattern matches
This file contains hidden or 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
/// Several types of consoles | |
type Console = | |
| Playstation_5 | |
| Xbox_Series_X | |
| Switch | |
with | |
member this.Name = | |
match this with | |
| Playstation_5 -> "Playstation 5" | |
| Xbox_Series_X -> "XBox Series X" | |
| Switch -> "Switch" | |
type GpuDetails = { ComputeUnits:int; Shaders:int } | |
with | |
/// AMD hardware has 64 shaders per compute unit | |
static member Create (numCU:int) = { ComputeUnits = numCU; Shaders = 64 * numCU } | |
/// Active patterns can execute some additional code and output data on the match. | |
/// Partial active patterns return an option for cases that don't "fit" the match. | |
/// Now a partial active pattern to show GPU details for consoles that have them | |
let (|GPU|_|) (console:Console) = | |
match console with | |
| Playstation_5 -> GpuDetails.Create 36 |> Some | |
| Xbox_Series_X -> GpuDetails.Create 52 |> Some | |
| Switch -> None // It has some GPU, but we don't have the details | |
/// Match for the GPU on all types of consoles, printing what GPU info we have available | |
for console in [ Xbox_Series_X; Playstation_5; Switch ] do | |
match console with | |
| GPU gpu -> Console.WriteLine $"{console.Name} has {gpu.ComputeUnits} compute units and {gpu.Shaders} shaders." | |
| _ -> () // Nothing executed when we don't have GPU information. |
Author
ninjarobot
commented
Apr 8, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment