The pattern matching wizard's thread

I ran across this on one of @quint 's slides in motoko BootCamp:

I tried it out and, sure enough, another tool for the tool box. I had no idea. Internet Computer Loading

Anyone else have any patterns that they use that make their lives easier? I’m embarrassed to say that I still feel like I don’t understand the full power of these even two years into using Motoko.

When I look at the list at Internet Computer Loading, I feel that there are things like maybe I have more to learn.

I guess the above is the object pattern and was sitting there all along, but I needed an example to really understand it. I’m still not really sure what Annotated Pattern is.

Who has some cool examples of patterns?

I found the “or” pattern handy when I wanted to merge the behavior of the #Ledger and # ICRC1 types in the Origyn NFT:


transaction_id := switch(details.token){
        case(#ic(token)){
          switch(token.standard){
            case(#Ledger or #ICRC1){
              //D.print("found ledger");
              let checker = Ledger_Interface.Ledger_Interface();
              .....

It would be great to have a thread we can point people to that are just learning pattern matching so they have some good examples to look at.

5 Likes

I was also unaware. Very cool pattern matching

This is a nice trick. The only gotchya is that since there are still two potential variant matches, Motoko won’t allow you to deconstruct any of the variants that were matched inside that specific or case statement (i.e. if there’s a value inside one or both of those variants, you need another switch to narrow it down and extract the value).

1 Like

You can find the slides here:
https://motoko.academy/custom/1

1 Like

It’s a bit more nuanced. It totally allows you to deconstruct as deep as you want to go inside an or-pattern. It merely doesn’t (currently) allow you to extract a value. For example,

case (#aNumber(42) or #something(_, {field1 = ?"text"} or {field2 = 100}))

is totally supported, but

case (#aNumber(n) or #aPair(n, _))

is not, as you cannot bind a variable inside an or-pattern. Supporting this has always been on the list of features to come eventually, though, and is allowed in many other languages with pattern matching.

1 Like