【发布时间】:2020-03-08 21:45:51
【问题描述】:
抱歉,但我是 scala 的新手……现在学习它。
我一直在尝试完成一项练习,要求如下:-
// 编写一个函数 isPerfectNumber,它接受整数输入并返回字符串输出。
// 判断一个数是否完美,完美则返回true,否则返回false
// 编写一个高阶函数 myHigherOrderFunction,它以 isPerfectNumber 和 intList 作为输入,返回一个字符串列表,如果数字是完美的,则包含输出 使用映射强>。
完美数字:
https://rosettacode.org/wiki/Perfect_numbers
just go to the scala section
我的代码:
object ListMapHigherOrder{
def main(args:Array[String])
{
val intRes = args.toList
val intList: List[Int] = intRes.map(_.toInt).toList
def isPerfectNumber(input: Int) :String =
{
var check_sum = ( (2 to math.sqrt(input).toInt).collect { case x if input % x == 0 => x + input / x} ).sum
if ( check_sum == input - 1 )
return "true"
else
return "false"
}
def myHigherOrderFunction(argFn: Int => String, argVal:List[Int]): List[String] = { argVal.map(argFn) }
println(myHigherOrderFunction(isPerfectNumber, intList))
}
}
代码执行:scala ScalaExcercise12.scala 1 6 13
预期输出:列表(假,真,假)
代码给出了预期的输出,我不确定后端测试是如何完成的......它只是通过了测试。
代码有问题吗? - 我确实想修复它,但我看不到任何错误/缺失,尤其是因为我得到了与期望相同的输出:(
【问题讨论】:
-
如果您的代码运行并产生预期的输出,那么您可以通过将其发布到Code Review 来获得反馈。 Stack Overflow 不适用于一般代码评估。
-
好的,我会把它贴在那里。
-
通常不鼓励同时使用
var和return(在此处不需要)
标签: scala