12.1 編寫函數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) = {
for (i <- low to high) yield (i, fun(i))
}
val x = values(x => x * x, -5, 4) //Vector((-5,25), (-4,16), (-3,9)...
12.2 如何用reduceLeft得到數組中的最大元素?
val array = Array(1, 2, 5, 4, 3)
array.reduceLeft((a, b) => if (a > b) a else b)
12.3 用to和reduceLeft實現階乘函數,不得使用循環或遞歸
val n = 9
1 to n reduceLeft(_ * _)
12.4 前一個實現需要處理一個特殊情況,即n<1的情況。展示如何用foldLeft來避免這個需要
val num = -9
(1 to num).foldLeft(1)(_ * _)
12.5 編寫函數largest(fun:(Int)=>Int,inputs:Seq[Int]),輸出在給定輸入序列中給定函數的最大值。舉例來說,largest(x=>10*x-x*x,1 to 10)應該返回25.不得使用循環或遞歸
def largestf(fun: (Int) => Int, inputs: Seq[Int]): Int = {
val res = inputs.reduceLeft((a, b) => if (fun(a) > fun(b)) a else b)
fun(res)
//inputs.map(fun).max
}
largestf(x => 10 * x - x * x, 1 to 10)
12.6 修改前一個函數,返回最大的輸出對應的輸入。舉例來說,largestAt(fun:(Int)=>Int,inputs:Seq[Int])應該返回5。不得使用循環或遞歸
def largest(fun: (Int) => Int, inputs: Seq[Int]): Int = {
val res = inputs.reduceLeft((a, b) => if (fun(a) > fun(b)) a else b)
res
}
largest(x => 10 * x - x * x, 1 to 10)
12.7 要得到一個序列的對偶很容易,比如:val pairs = (1 to 10) zip (11 to 20)假定你想要對這個序列做某中操作—比如,給對偶中的值求和,但是你不能直接使用:pairs.map(_ + )函數 + _ 接受兩個Int作爲參數,而不是(Int,Int)對偶。編寫函數adjustToPair,該函數接受一個類型爲(Int,Int)=>Int的函數作爲參數,並返回一個等效的, 可以以對偶作爲參數的函數。舉例來說就是:adjustToPair(_ * _)((6,7))應得到42。然後用這個函數通過map計算出各個對偶的元素之和
/***這個函數不太懂,特別是調用那裏,不明白((6,7))要2個括號***/
def adjustToPair(fun: (Int, Int) => Int): ((Int, Int)) => Int = {
(tuple: (Int, Int)) => fun(tuple._1, tuple._2)
}
val b = adjustToPair(_ * _)
val c = b(6, 7) //((6,7))也對
val d = adjustToPair(_ * _)((6,7))
12.8 在12.8節中,你看到了用於兩組字符串數組的corresponds方法。做出一個對該方法的調用,讓它幫我們判斷某個字符串數組裏的所有元素的長度是否和某個給定的整數數組相對應
val f = Array("red", "black", "blue")
val g = Array(3, 5, 4)
f.corresponds(g)(_.length == _) //res5: Boolean = true
略