2
我是新来scala和函数式编程。我正在尝试通常的初学者应用程序和脚本(显然使用了一些过度技术)如何让此代码更加功能
反正我有一个计算器的代码,它需要参数和一个开关来指定要在参数上使用的操作。
object Main {
def main(args: Array[String]): Unit = {
var calc = calculate("" , _:List[Int])
var values:List[Int] = List()
if(args.size < 1) println("No arguments supplied") else{
args collect {_ match{
case arg if arg.contains("-") => {
if(values.size>0){
calc(values)
values = List()}
calc = calculate(arg , _:List[Int])
}
case arg => {
try{
val value=arg.toInt
values = values ::: List(value)
}catch{case e:NumberFormatException=>println("\nError:Invalid argument:\""+arg+"\"\nCannot convert to Integer.\n")}
}
}
}
calc(values)
}
}
def sum(values:List[Int]) { println("The sum is:"+(values.foldLeft(0)((sum,value) => sum + value))) }
def subtract(values:List[Int]) {
val initial:Int = values(0)
var total:Int = 0
for(i <- 1 until values.size){
total = total + values(i)
}
val diff:Int = initial - total
println("The difference is:"+diff)
}
def calculate(operation:String,values:List[Int]) = operation match {
case "-sum" => sum(values)
case "-diff" => subtract(values)
case _ => println("Default operation \"Sum\" will be applied");sum(values)
}
}
id想要找到更好的方法就像去除try catch语句一样。
构建此应用程序的更好方法将非常受欢迎。
相当优雅的做事方式!由于没有添加新的_val_或_var_,因此也更加高效。感谢** om-nom-nom ** – korefn
可能希望编译'parseArguments(args,“”)'到'parseArguments(args.toList,“”“)'在2.9.2中不能编译,因为这个转换似乎不是隐含的。 – korefn
@ korefn是的,在我的脑海里有这个想法,但是当我写代码的时候不知何故错过了它。 –