Can `match` in Racket have patterns with variables from an outer scope?

瘦欲@ 提交于 2019-12-21 07:14:04

问题


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).


回答1:


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.



来源:https://stackoverflow.com/questions/29978583/can-match-in-racket-have-patterns-with-variables-from-an-outer-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!