It is important to note that A and B are constructors of the same type Something . Thus, you will receive a warning about an inexhaustible pattern if you try to use cases A and B separately.
IMO, deconstructing all DU cases is a good idea because it is type safe and makes you think about handling these cases even if you don't want to. A problem may arise if you have to deconstruct the DU again the same way. In this case, defining map and fold functions on DU might be a good idea:
let mapSomething fa fb = function | A(i) -> fa i | B(s, i) -> fb si
Please refer to @Brian 's excellent catamarphism series to learn about the DU fold.
It also says your example is fine. What you are actually processing are the string and int values โโafter deconstruction.
You can use Active Templates to share two cases:
let (|ACase|) = function A i -> i | B _ -> failwith "Unexpected pattern B _" let (|BCase|) = function B(s, i) -> (s, i) | A _ -> failwith "Unexpected pattern A _" let doSomethingWithA (ACase i) = ....
but the output type doSomethingWithA remains the same, and you get an exception when passing B _ function. So itโs wrong to do IMO.
source share