Scala 斯卡拉有警卫吗?
几天前我开始学习scala,在学习它的时候,我将它与我熟悉的其他语言如(,)进行比较。Scala有可用的序列吗Scala 斯卡拉有警卫吗?,scala,functional-programming,Scala,Functional Programming,几天前我开始学习scala,在学习它的时候,我将它与我熟悉的其他语言如(,)进行比较。Scala有可用的序列吗 我在Scala中进行了模式匹配,但是否有任何概念等同于使用否则和所有的警卫?是的,它使用关键字如果。在Scala之旅的底部附近: def isIdentityFun(term: Term): Boolean = term match { case Fun(x, Var(y)) if x == y => true case _ => false } (页面上没有提到
我在Scala中进行了模式匹配,但是否有任何概念等同于使用
否则
和所有的警卫?是的,它使用关键字如果
。在Scala之旅的底部附近:
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
(页面上没有提到这一点,可能是因为本次巡演是如此快速的概述。)
在Haskell中,
否则
实际上只是一个绑定到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
}
def-boundedInt(最小值:Int,最大值:Int):Int=>Int={
如果n>max=>max,则为案例n
案例n如果n min
案例n=>n
}
请注意,您只需在没有保护的情况下指定模式,而不是使用
或-子句。简单的答案是否定的。它并不完全符合您的要求(与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))
def func(x:Int,y:Int):字符串=(x,y)匹配{
大小写(_,0)|(0,_)=>“零”
如果x>-1=>“正数”,则使用大小写(x,x)
如果y<0=>“负数”,则为大小写(uu,y)
案例(,)=>“无法分类”
}
println(func(10,-1))
println(函数(-10,1))
println(func(-10,0))
在这种情况下,n
将是什么,请为上述内容提供一个工作示例。@Jetn
将是函数的参数这是使用函数的一个例子。