22

Consider the following example:

#lang racket

(match '(cat . doge)
  [`(,a . ,b)
   (match b
     [a #t]
     [_ #f])]
  [_ "Not a pair"])

This is what I might write if I wanted to match pairs where the head and tail are the same. This doesn't work though because the second a is bound as a new variable (and matches anything). Are there any pattern forms which allow me to use the previously bound a from the outer scope?

I know this can be achieved in the following way

(match* ('cat 'doge)
  [(a a) #t]
  [(_ _) #f])

but I still would like to know if there is a way to get that variable from the outer scope (or if there is a reason for not doing so, like some potential name collision problem or something).

Chris Brooks
  • 725
  • 6
  • 15

1 Answers1

21

Use ==:

(match '(cat . doge)
  [`(,a . ,b)
   (match b
     [(== a) #t]
     [_      #f])]
  [_ "Not a pair"])

Due to the placement in the docs, == is easy to overlook.

Greg Hendershott
  • 16,100
  • 6
  • 36
  • 53
soegaard
  • 30,661
  • 4
  • 57
  • 106
  • 3
    Also easy to overlook is `#:when`. For example, the clause could be `[(cons a b) #:when (eq? a b) #t]`. Of course `==` is simpler in this example. – Greg Hendershott May 01 '15 at 00:40