Motoko casting to subtype with trap

Motoko has some trapping conversion such as Nat32.fromNat that trap dynamically if the value would lose precision.

I am trying to do something similar for casting from variant type {#a; #b; #c} to subtype {#a; #b}. What I have is this code:

import Debug "mo:base/Debug";

type X = {#a; #b; #c};
type Y = {#a; #b};

func(x : X) : Y {
  switch (x) {
    case (#a) { #a };
    case (#b) { #b };
    case (_) { Debug.trap("") };
  };
}

Is there any way to write this more concisely? I wanted to use something like case (#a or #b) but that doesn’t work. The new let .. else construct doesn’t help either.

3 Likes

I had a similar question, my guess is no based off the response to mine

1 Like

Yes. The same question, indeed. Thanks for sending the link!

1 Like