Short Variant Checking

Is there a way to quickly check if a value is of a variant type? In the following example it would be great if I could write something shorter.such as keep(p => p == Additional(_))

let options = package =>
package.treatments->List.keep(p =>
  switch p.value {
  | Additional(_) => true
  | _ => false
  }
)

Not sure you can’t use a wildcard in equality. You can create a helper though:

let isAdditional  = p =>
  switch p.value {
  | Additional(_) => true
  | _ => false
  }

But I think it’s a good idea to make that switch exhaustive. Then, if you add another variant to the type, or remove a variant, you’re going to be forced to revisit the helper, and this could save you from your checks becoming nonsensical.

2 Likes

I agree, I think in most cases _ is a footgun. Ok it might be a bit annoying to list all the cases now but what’s it going to take you – 20 seconds? A minute? Compare that to the loss of knowledge at the type level of your program, and the loss of refactoring support from the compiler.

2 Likes

I think that is fair. It’s the edge case that I only want to filter to one variant. I will be exhaustive.

Thank you!

Could maybe do some higher order modelling though with GADT’s. :upside_down_face: Still not familiar enough with polymorphic variants though so just something to explore later!

https://rescript-lang.org/try?code=C4TwDgpgBMULxQNoGICCUA+VkCEC6AUAQDYSwCGAXFMQJYDOwAPIk2ngHzw0PADeaAL4kyUAEbU6jFm1SduU-rkFA