Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives when pattern matching in Racket

I want to match one of the following two lists in Racket (formerly PLT Scheme):

'(somename : (_ptr o sometype))

or

'(somename : (_ptr io sometype))

As you can see, the only difference is the literals 'o and 'io in the embedded list.

I can see two basic ways to do this.

Either:

(match myexpr 
    [(list name ': (list '_ptr 'o _)) name]
    [(list name ': (list '_ptr 'io _)) name]
    [_ 0])

which seems like duplication of the effort, but is very clear. Or:

(match myexpr 
    [(list name ': (list '_ptr mode _)) 
      (if (or (eq? mode 'o) 
              (eq? mode 'io))
     name
     0)]
    [_ 0])

which avoids the almost duplicated patterns, but is much less clear.

My question is, is there a way to specify alternatives in racket pattern matching, something along the lines of {'o | 'io}? And, if not, which of the two ways outlined above would be the most idiomatic Racket way?

like image 913
corvuscorax Avatar asked Aug 15 '26 16:08

corvuscorax


1 Answers

Use an or pattern (or 'o 'io). And of course, don't forget that all of this is documented.

like image 131
Eli Barzilay Avatar answered Aug 17 '26 07:08

Eli Barzilay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!