如何模式匹配到大写变量? [英] How to pattern match into an uppercase variable?

查看:62
本文介绍了如何模式匹配到大写变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Scala 中有一个返回元组的方法,假设该方法称为测试".那我想做

I have a method in Scala that returns a tuple, let's say the method is called 'test'. Then I want to do

val (X,Y) = test()

但是,模式匹配仅在 Scala 中变量名称为小写时才有效,即:

However, the pattern-matching only works in Scala when the variable names are lowercase, ie:

val(_X,_Y) = test(); val X = _X; val Y = _Y

... 工作正常,但很丑,而且不简洁.由于 X 和 Y 是矩阵,我真的不想使用小写变量.(例如在 scipy 和 matlab 中,我不会有这样的限制).

... works ok, but is ugly, and not terse. Since X and Y are matrices, I don't really want to have to use lowercase variables. (In scipy and matlab, I wouldn't have such a restriction for example).

我认为有一些方法可以确保小写变量的行为与大写变量一样,即通过执行`x`.也许有某种方法可以使大写变量表现得像小写变量?所以,这就是我的问题:在 Scala 中是否有某种方式可以将模式直接匹配到大写变量中?

I think there is some way to make sure lowercase variables behave like uppercase ones, ie by doing `x`. Perhaps there is some way of making uppercase variables behave like lowercase ones? So, that is my question: is there some way of pattern matching directly into uppercase variables in Scala?

推荐答案

简短的回答是不要.

语法约定使您的代码易于他人阅读和理解.Scala 的约定是变量以小写开头,常量和类以大写开头.违反这一规定,不仅会遇到模式匹配问题,而且代码的可读性也会降低.(相信我,如果你不得不阅读不关心这些约定的其他人编写的代码,你会诅咒那个人.)

Syntax conventions make your code readable and understandable for others. Scala's convention is that variables start with lower-case and constants and classes start with upper-case. By violating this, not only you get problems like pattern-matching issues, your code becomes less readable. (Believe me, if you ever have to read code written by someone else who didn't care for such conventions, you'll be cursing that person.)

如果你想强调变量是矩阵,我建议你使用 xMatrixyMatrix 或类似的东西.这将清楚表明它们是变量并且它们代表矩阵.

If you want to emphasize that the variables are matrices, I suggest you to use xMatrix and yMatrix or something like that. This will make clear that they're variables and that they represent matrices.

或者创建一个特定于您的项目的约定,所有矩阵变量都将以M"结尾,例如 xMyM.

Or create a convention specific to your project that all matrix variables will end with let's say "M", like xM and yM.

如果能让你的代码可读,那么输入几个字符是值得的.

这篇关于如何模式匹配到大写变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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