- 编写函数values(fun:(Int)=>Int,low:Int,high:Int),该函数输出一个集合,对应给定区间内给定函数的输入和输出。比如,values(x=>x*x,-5,5)应该产出一个对偶的集合(-5,25),(-4,16),(-3,9),…,(5,25)
def values( fun:(Int) => Int, low :Int, high:Int)={
var arr = List[(Int,Int)]()
low to high foreach{
num => arr = (num,fun(num)) :: arr
}
arr
}
values(x => x*x, -5,5).foreach(print(_))
//输出结果为:(5,25)(4,16)(3,9)(2,4)(1,1)(0,0)(-1,1)(-2,4)(-3,9)(-4,16)(-5,25)
- 如何用reduceLeft得到数组中的最大元素?
val a=Array(1.1,2.1,3.1,0.1,4.1)
a.reduceLeft((a,b) => if(a>b) a else b)
- 用to和reduceLeft实现阶乘函数,不得使用循环或递归
println(1 to 3 reduceLeft(_ * _))