Scala 中的嵌套模式匹配
Nested pattern matching in Scala
我是 Scala 的新手,我想了解模式匹配的工作原理。所以我写了这段基本代码,它返回了预期的结果:
def test(choice: Int): String = choice match {
case x if x > 0 && x%2 == 0 => "positive even number"
case x if x > 0 && x%2 != 0 => "positive odd number"
case 0 => "null"
case x if x < 0 && x%2 == 0 => "negative even number"
case x if x < 0 && x%2 != 0 => "negative odd number"
}
现在我想做一些更复杂的事情:
def test(choice: Int): String = choice match {
case x if x%2 == 0 => x match {
case y if y > 0 => "even and positive number"
case y if y < 0 => "even and negative number"
}
case 0 => "null"
case x if x%2 != 0 => x match {
case y if y > 0 => "odd and positive number"
case y if y < 0 => "odd and negative number"
}
}
但是失败了。这是控制台上的错误消息:
scala> def test(choice: Int): String = choice match {
|
| case x if x%2 == 0 => x match {
| case y if y > 0 => "even and positive number"
| Display all 600 possibilities? (y or n)
[...]
| if y < 0 => "even and negative number"
<console>:5: error: '(' expected but identifier found.
if y < 0 => "even and negative number"
^
[...]
有人可以告诉我我做错了什么,并详细说明我对 Scala 的总体误解,尤其是 match
方法。
在您的第一个代码中,您在前两种情况下测试 x>0,然后测试 0 本身。
在第二个代码中,您不测试 x>0,但 x%2 == 0 已经匹配 x = 0,并且不考虑第二个外部匹配。
如果您将明确的 0 匹配放在最上面,它可能会起作用,但我没有寻找第二个错误,只匹配了我能找到的第一个错误。 :)
它为我编译。案例的顺序对于编译的成功无关紧要(但是,case 0
分支永远不会匹配,因为 case x if x%2==0
匹配 x=0
。您可能希望 case 0
分支第一个)
我认为您的问题是因为在终端中使用制表符而不是空格。
如果您在项目的文件中使用此代码,它也会编译。如果你想让它在控制台中工作,你可以:
- 在粘贴代码之前将制表符转换为空格
- 使用
:paste
命令在 REPL 中进入粘贴模式,粘贴代码并使用 Ctrl-D
退出粘贴模式(或者 REPL 告诉您的任何组合 - 这就是 Mac).
我是 Scala 的新手,我想了解模式匹配的工作原理。所以我写了这段基本代码,它返回了预期的结果:
def test(choice: Int): String = choice match {
case x if x > 0 && x%2 == 0 => "positive even number"
case x if x > 0 && x%2 != 0 => "positive odd number"
case 0 => "null"
case x if x < 0 && x%2 == 0 => "negative even number"
case x if x < 0 && x%2 != 0 => "negative odd number"
}
现在我想做一些更复杂的事情:
def test(choice: Int): String = choice match {
case x if x%2 == 0 => x match {
case y if y > 0 => "even and positive number"
case y if y < 0 => "even and negative number"
}
case 0 => "null"
case x if x%2 != 0 => x match {
case y if y > 0 => "odd and positive number"
case y if y < 0 => "odd and negative number"
}
}
但是失败了。这是控制台上的错误消息:
scala> def test(choice: Int): String = choice match {
|
| case x if x%2 == 0 => x match {
| case y if y > 0 => "even and positive number"
| Display all 600 possibilities? (y or n)
[...]
| if y < 0 => "even and negative number"
<console>:5: error: '(' expected but identifier found.
if y < 0 => "even and negative number"
^
[...]
有人可以告诉我我做错了什么,并详细说明我对 Scala 的总体误解,尤其是 match
方法。
在您的第一个代码中,您在前两种情况下测试 x>0,然后测试 0 本身。
在第二个代码中,您不测试 x>0,但 x%2 == 0 已经匹配 x = 0,并且不考虑第二个外部匹配。
如果您将明确的 0 匹配放在最上面,它可能会起作用,但我没有寻找第二个错误,只匹配了我能找到的第一个错误。 :)
它为我编译。案例的顺序对于编译的成功无关紧要(但是,case 0
分支永远不会匹配,因为 case x if x%2==0
匹配 x=0
。您可能希望 case 0
分支第一个)
我认为您的问题是因为在终端中使用制表符而不是空格。
如果您在项目的文件中使用此代码,它也会编译。如果你想让它在控制台中工作,你可以:
- 在粘贴代码之前将制表符转换为空格
- 使用
:paste
命令在 REPL 中进入粘贴模式,粘贴代码并使用Ctrl-D
退出粘贴模式(或者 REPL 告诉您的任何组合 - 这就是 Mac).