Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
Pattern matching with Generics
I propose we permit pattern matching on generic types.
type Packet() = class end type KeepalivePacket() = inherit Packet() let send<'T when 'T :> Packet>(packet:'T) = match packet with | :? KeepalivePacket as keepalive -> () // Do stuff with keepalive
The existing way of approaching this problem in F# is to change it to an if-statement on type objects.
This was already implemented in C# 7.1. We should do so too.
Pros and Cons
The advantages of making this adjustment to F# are
The disadvantages of making this adjustment to F# are none that I can think of.
Estimated cost (XS, S, M, L, XL, XXL): S
Affidavit (please submit!)
Please tick this by placing a cross in the box:
Please tick all that apply:
I would consider (at least outside the compiler) matching on types and downcasting to be a code smell, and the extra difficulty of using if-statements on type objects here may provide a good deterrent. Do others consider this type of code to be proper?
Note that the compiler can do this statically, but it requires a hidden switch (I forgot which it was), that would allow you to match over types in an SRTP way. An example is the current
The simpler workaround is to just use boxing.
Isn't it the switch that's used to compile the core library? i.e. the one that's used to make the (+) operator work with all number types
@jwosty, yes, I think so, though the way I understand it, it's essentially an extension to SRTP. One option would be to allow that syntax outside the compiler, but I've experimented in the past with that hidden compiler switch. At least it used to work, but had some limitations.