Skip to content

Instantly share code, notes, and snippets.

@ninjarobot
Last active April 8, 2021 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ninjarobot/a0f8792a1089a6df2fd0f42c5ad22746 to your computer and use it in GitHub Desktop.
Save ninjarobot/a0f8792a1089a6df2fd0f42c5ad22746 to your computer and use it in GitHub Desktop.
Using partial active patterns to return calculated data in pattern matches
/// 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.
@ninjarobot
Copy link
Author

XBox Series X has 52 compute units and 3328 shaders.
Playstation 5 has 36 compute units and 2304 shaders.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment