为什么在替代模式中不允许使用变量? [英] Why are variables not allowed in alternative patterns?

查看:51
本文介绍了为什么在替代模式中不允许使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常你有对称"匹配并且想写这样的东西:

Often you have "symmetric" matches and want to write things like:

def g(p:(Int,Int)) = p match {
  case (10,n) | (n,10) => println(n)
  case _ => println("nope")
}

这是不允许的,但是如果每个选项都有相同的变量相同的类型,这应该不是问题,因为它可以被翻译成分离案例:

This is not allowed, but if every alternative has the same variables with the same types, this shouldn't be a problem, as it could be translated to separate cases:

def g(p:(Int,Int)) = p match {
  case (10,n) => println(n)
  case (n,10) => println(n)
  case _ => println("nope")
}

那么为什么我们有这个限制?

So why do we have this restriction?

推荐答案

可能是因为实施需要一些时间,而这些时间最好花在其他地方.它还会不必要地增加语言及其编译器的复杂性.正如您已经提到的,这个问题很容易避免.避免该问题的另一种方法是编写自定义提取器:

Likely because it would take some time to implement and that time is better spent elsewhere. It would also unnecessarily add to the complexity of the language and its compiler. As you already mentioned, the problem can easily be avoided. One other way to avoid the problem is to write a custom extractor:

object ThisOrThat {
  def unapply(p:(Int,Int)):Option[Int] = p match {
    case (10, n) => Some(n)
    case (n, 10) => Some(n)
    case _ => None
  }
}

这篇关于为什么在替代模式中不允许使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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