What's difference between case and match?

by user8314628   Last Updated December 06, 2018 15:26 PM

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))
      [(list a b c) 'sum-is-not-six]))
> (m '(1 2 3))

> (m '(2 3 4))

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?

Tags : match case racket

Answers 1

You said it yourself, match does pattern matching whereas case only checks if a value belongs in one of several lists of possible values.

All that case does is syntax sugar for a cond with multiple conditions, for example:

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

... is equivalent to:

(let ((val (+ 7 5)))
  (cond ((or (equal? val 1) (equal? val 2) (equal? val 3))
        ((or (equal? val 10) (equal? val 11) (equal? val 12))
        (else 'other)))
Óscar López
Óscar López
December 06, 2018 15:25 PM

Related Questions

ERROR 2998: Unhandled internal error. null - Apache Pig

Updated September 14, 2016 08:12 AM

Racket: Insert new nodes into a binary search tree

Updated November 05, 2017 04:26 AM

place-image not defined in Dr-Racket

Updated September 03, 2018 13:26 PM

Work with binary search trees in Racket

Updated November 12, 2017 15:26 PM