Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 模式匹配bigint_Scala - Fatal编程技术网

Scala 模式匹配bigint

Scala 模式匹配bigint,scala,Scala,此阶乘实现适用于特定大小的数字: def factorial(n:Int):Int = n match { case 0 => 1 case x => x * factorial(x - 1) } 我尝试使用BigInt使它适用于任何大小的数字 val zero = BigInt(0) def factorial(n:BigInt):BigInt = n match { case zero => 1 case x => x * facto

此阶乘实现适用于特定大小的数字:

def factorial(n:Int):Int = n match {
    case 0 => 1
    case x => x * factorial(x - 1)
}
我尝试使用BigInt使它适用于任何大小的数字

val zero = BigInt(0)
def factorial(n:BigInt):BigInt = n match {
    case zero => 1
    case x => x * factorial(x - 1)
}
无论n的值是多少,对factorial的每次调用都返回1。我假设这是因为第一个案例总是匹配的,并通过将其更改为

case zero => 22
并验证每个输入返回了22

所以我的两个问题是

  • 为什么第一个案例总是匹配的
  • 有没有办法让这个函数的BigInt版本在坚持模式匹配的同时工作

  • 您应该将
    zero
    重命名为
    zero
    ,或者像这样使用它:

    case `zero` => 1
    

    要与变量匹配,请将其包装为“`”


    您还可以使val以大写字母开头,如
    Zero
    。您能解释一下这种语法吗?我是新手scala@jtkSource看变量还是常数?在里面
    val zero = BigInt(0)
    def factorial(n:BigInt):BigInt = n match {
        case `zero` => 1
        case x => x * factorial(x - 1)
    }