Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's difference between case and match?

Tags:

case

match

racket

I was confusing about the difference between match and case. In the document, it mentions that match supports general pattern matching.

> (define (m x)
    (match x
      [(list a b c)
       #:when (= 6 (+ a b c))
       'sum-is-six]
      [(list a b c) 'sum-is-not-six]))
> (m '(1 2 3))
'sum-is-six

> (m '(2 3 4))
'sum-is-not-six 

For this example, I thought I could rewrite it using case expression. But seems it's quite complicated. I have to get the length of the input x, and maybe a lambda function to get the sum of the elements of x and compare it with 6.

So I guess we prefer match when doing pattern matching. Is it true? Any difference other than that?

like image 262
user8314628 Avatar asked Dec 06 '18 10:12

user8314628


1 Answers

You said it yourself, match does general pattern matching (a very powerful concept!) whereas case only checks if a value belongs in one of several lists of possible (implicitly quoted) values. All that case does is syntactic sugar for a cond with multiple conditions, for example:

(case (+ 7 5)
  [(1 2 3) 'small]
  [(10 11 12) 'big]
  [else 'other])

... is roughly equivalent to:

(let ((val (+ 7 5)))
  (cond ((or (equal? val 1) (equal? val 2) (equal? val 3))
        'small)
        ((or (equal? val 10) (equal? val 11) (equal? val 12))
        'big)
        (else 'other)))

Whereas match does some complex matching; it checks if a value is one of several possible patterns, it's not only about comparing values for equality, it also checks the type and "shape" of the value against the pattern, and we can even add additional constraints using #:when. To see how complex this can be check under the grammar part of match's documentation.

like image 73
Óscar López Avatar answered Oct 02 '22 23:10

Óscar López