Conditional pattern matching in Racket

Since all the examples are in the list guide, it’s hard for me to understand how to use pattern matching in Racket to write conditional matching, like OCaml, 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 do I write something like this in Racket?

Thanks.

+6
source share
2 answers

racket/match library include pattern matching that can use arbitrary predicates with a pattern ? . Along with and , you should be able to make the Racket token behave. Although I'm a little weak in my OCaml, I think the following translation of the above code matches its meaning:

 (define (my-read #:var-a var-a var-b s) (match (string-ref s 0) [(and _ (? (lambda (_) (>= var-b (+ var-a 4))))) "do something"] [(and '#\a (? (lambda (_) (< var-b 0)))) "do something else"])) ;; Exercising the first case: (my-read #:var-a 50 60 "blah") ;; Exercising the second case: (my-read #:var-a 50 -40 "alphabet") 

Pairing ? has an implicit and built into it, so the code can be expressed a little more succinctly, like:

 (define (my-read #:var-a var-a var-b s) (match (string-ref s 0) [(? (lambda (_) (>= var-b (+ var-a 4)))) "do something"] [(? (lambda (_) (< var-b 0)) #\a) "do something else"])) 

In both cases, the lambdas do not look there, which corresponded, so I just called them _ to denote non-exit. But you can imagine more complex models where predicates could take deep care of what exactly matched.

Eli suggests using a generic cond here, as there is no meaningful pattern matching in the code. I agree. The code will look like this:

 (define (my-read #:var-a var-a var-b s) (cond [(>= var-b (+ var-a 4)) "do something"] [(and (char=? (string-ref s 0) #\a) (< var-b 0)) "do something else"])) 
+10
source

Template compatibility can be easily translated into a test sequence; there is no language in which you cannot do this.

What makes OCaml (and probably Haskell) compatible is that the compiler will convert the code to the optimal test sequence whenever possible (i.e. the program will never double check the same condition, at least when you avoid when ).

+3
source

Source: https://habr.com/ru/post/908281/


All Articles