Racket 中的“match"可以有来自外部作用域的变量的模式吗? [英] Can `match` in Racket have patterns with variables from an outer scope?

查看:61
本文介绍了Racket 中的“match"可以有来自外部作用域的变量的模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例:

#lang racket

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

如果我想匹配头部和尾部相同的对,这就是我可能会写的.但是这不起作用,因为第二个 a 被绑定为一个新变量(并匹配任何内容).是否有任何模式形式允许我从外部范围使用先前绑定的 a?

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

推荐答案

使用 ==:

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

由于在文档中的位置,== 很容易被忽视.

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

这篇关于Racket 中的“match"可以有来自外部作用域的变量的模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆