【发布时间】:2011-01-17 00:54:34
【问题描述】:
我几天前开始学习 scala,在学习它时,我将它与我熟悉的其他 functional programming 语言(如 (Haskell, Erlang) 进行比较。 Scala 有可用的guard 序列吗?
我在 Scala 中进行了模式匹配,但有没有任何概念等同于 otherwise 和所有的守卫?
【问题讨论】:
标签: scala functional-programming
我几天前开始学习 scala,在学习它时,我将它与我熟悉的其他 functional programming 语言(如 (Haskell, Erlang) 进行比较。 Scala 有可用的guard 序列吗?
我在 Scala 中进行了模式匹配,但有没有任何概念等同于 otherwise 和所有的守卫?
【问题讨论】:
标签: scala functional-programming
是的,它使用关键字if。来自 A Tour of Scala 的 Case Classes 部分,靠近底部:
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
(Pattern Matching 页面上没有提到这一点,可能是因为巡回赛的概述如此之快。)
在 Haskell 中,otherwise 实际上只是一个绑定到True 的变量。所以它不会为模式匹配的概念增加任何力量。您只需在没有防护的情况下重复您的初始模式即可获得它:
// if this is your guarded match
case Fun(x, Var(y)) if x == y => true
// and this is your 'otherwise' match
case Fun(x, Var(y)) if true => false
// you could just write this:
case Fun(x, Var(y)) => false
【讨论】:
是的,有模式守卫。它们是这样使用的:
def boundedInt(min:Int, max: Int): Int => Int = {
case n if n>max => max
case n if n<min => min
case n => n
}
请注意,您只需指定不带保护的模式,而不是 otherwise-clause。
【讨论】:
n 是什么,请给出一个工作示例。
n 将是函数的参数。 Here是一个使用函数的例子。
简单的答案是否定的。它不是您正在寻找的(与 Haskell 语法完全匹配)。你可以使用 Scala 的“匹配”语句和一个守卫,并提供一个通配符,比如:
num match {
case 0 => "Zero"
case n if n > -1 =>"Positive number"
case _ => "Negative number"
}
【讨论】:
我偶然发现这篇文章是为了寻找如何将守卫应用于具有多个参数的匹配,这不是很直观,所以我在这里添加一个随机示例。
def func(x: Int, y: Int): String = (x, y) match {
case (_, 0) | (0, _) => "Zero"
case (x, _) if x > -1 => "Positive number"
case (_, y) if y < 0 => "Negative number"
case (_, _) => "Could not classify"
}
println(func(10,-1))
println(func(-10,1))
println(func(-10,0))
【讨论】: