Scala練習之高階函式
阿新 • • 發佈:2018-12-25
- 編寫函式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(_ * _))