F#: Pattern Matching on Container Type

Intro

I recently learned how to pattern match on object types. This may be necessary at times or could be an issue with one’s design. In either case, I will attempt to articulate how to pattern match on the container type of union cases within a discriminated union.

The Pattern Construct “:?”

In this example, I created a vehicle type with some union cases and created a function called isVehicle.

type Vehicle = 
    | Car
    | Tank
    | Helicopter

let isVehicle = fun (a:obj) ->; match a with
                               | 😕 Vehicle ->; "Is a vehicle" // on word press ":?" shows as a smiley face
                               | _         ->; "Is NOT a vehicle"

Car |>; isVehicle

The isVehicle function requires the value argument to be annotated with type object in order for pattern matching on types to work correctly. We then use the pattern construct “:?” to match on types.

Conclusion

In conclusion, I recently learned how to pattern match on object types. This may be necessary at times or could be an issue with one’s design. In either case, I attempted to articulate how to pattern match on the container type of union cases within a discriminated union.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: