简体   繁体   English

Scala阶乘语法错误

[英]Scala factorial syntax error

I wrote the following code: 我写了以下代码:

def factorial(x: Int, factorial( x => { if (x == 0) 1 else x * factorial(x - 1) })): Int = factorial(3)

But got the error: 但是得到了错误:

<console>:1: error: ':' expected but '(' found.

This part of the code makes sense (syntactically, at least): 这部分代码有意义(至少在语法上):

def factorial(...): Int = factorial(3)

What goes in the ... are the function's arguments. ...中的内容是函数的参数。 You were starting off fine with x:Int 您刚开始使用x:Int

def factorial(x: Int, ...): Int = factorial(3)

But then it kind of goes off the rails syntactically with factorial(x=>{if(x==0)1 else x*factorial(x-1)}) . 但是然后,它在某种程度上与factorial(x=>{if(x==0)1 else x*factorial(x-1)})脱离了语法。 I don't really know what to say about that, except that it's definitely not a function argument. 我真的不知道该说些什么,除了它绝对不是函数参数。 That's an expression , which is the sort of thing you'd put in the function body (after the = ), not in an argument list. 那是一个表达式 ,这是您要放在函数体内(在= )而不是参数列表中的某种东西。

You have factorial as a param item for your def, that is incorrect. 您将factorial作为def的参数项,这是不正确的。 Try: 尝试:

def factorial(x:Int): Int =
  if (x == 0) 1
  else x * factorial(x - 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM