Since all the examples in the guide are with lists, I find it difficult to see how to use pattern matching in Racket to write conditional matching like OCaml does, for example:
read ~var_a var_b s = match s.[0] with
| _ when var_b >= var_a + 4 ->
(* Do something *)
| "a" when is_negative var_b ->
(* Do something else *)
...
How would I write something similar in Racket?
Thanks.
The
racket/matchlibrary includes pattern matching that can use arbitrary predicates through the?pattern. Along withand, you should be able to get Racket’s matcher to behave. Although I’m a little weak in my OCaml, I think the following translation of the code above matches its meaning:The
?matcher has an implicitandembedded within it, so the code can be expressed slightly more succinctly as:In both, the lambdas in there aren’t watching what got matched, so I just named them
_to denote a don’t-care. But you can imagine more sophisticated patterns where the predicates could care deeply about what exactly got matched.Eli suggests using a general
condhere, since there isn’t any significant pattern matching in the code. I agree. The code would look like this: