1 编写函数values(fun: (Int) => Int, low: Int, high: Int),该函数输出一个集合,对应给定区间内给定函数的输入和输出。比如,values(x => x * x, -5, 5)应该产出一个对偶的集合(-5, 25), (-4, 16), (-3, 9), …, (5, 25)
var arr = ArrayBuffer[(Int, Int)]()
def values(fun: (Int) => Int, low: Int, high: Int) {
for (elem <- low to high)
arr += ((elem, fun(elem)))
}
values(x => x * x, 5, 10)
arr map (println)
2 如何用reduceLeft得到数组中的最大元素?
val arr = Array(3, 6, 6, 0, 1)
def f(a: Int, b: Int): Int = {
if (a > b) a
else b
}
println(arr.reduceLeft(f))
3 用to和reduceLeft实现阶乘函数,不得使用循环或递归
def f(n:Int){
println(1 to n reduceLeft (_ * _))
}
4 前一个实现需要处理一个特殊情况,即n<1的情况。展示如何用foldLeft来避免这个需要。(在scaladoc中查找foldLeft的说明。它和reduceLeft很像,只不过所有需要结合在一起的这些值的首值在调用的时候给出。)
println((1 to n).foldLeft(1)(_ * _))
5 编写函数largest(fun: (Int) => Int, inputs: Seq[Int]),输出在给定输入序列中给定函数的最大值。举例来说,largest(x => 10 * x - x * x, 1 to 10)应该返回25。不得使用循环或递归
def largest(fun: (Int) => Int, inputs: Seq[Int]) {
println(inputs.map { fun }.max)
}
largest(x => x * x, (1 to 5))
6 修改前一个函数,返回最大的输出对应的输入。举例来说,largestAt(fun: (Int) => Int, inputs: Seq[Int])应该返回5。不得使用循环或递归
def largest(fun: (Int) => Int, inputs: Seq[Int]) {
inputs.map { x => (x, fun(x)) }.
reduceOption((x, y) => if (x._1 > y._1) x else y).
map { x => println(x._1) }
}
largest(x => x * x, (1 to 5))
7 要得到一个序列的对偶很容易,比如:val pairs = (1 to 10) zip (11 to 20)假定你想要对这个序列做某种操作,比如,给对偶中的值求和,但是你不能直接使用:pairs.map( + )函数 _ + _ 接受两个Int作为参数,而不是(Int, Int)对偶。编写函数adjustToPair,该函数接受一个类型为(Int, Int) => Int的函数作为参数,并返回一个等效的, 可以以对偶作为参数的函数。举例来说就是:adjustToPair(_ * _)((6, 7))应得到42。然后用这个函数通过map计算出各个对偶的元素之和
def ajustToPair(fun: (Int, Int) => Int) = (t: Tuple2[Int, Int]) => {
fun(t._1, t._2)
}
println(ajustToPair(_ + _)(10, 4))
8 在12.8节中,你看到了用于两组字符串数组的corresponds方法。做出一个对该方法的调用,让它帮我们判断某个字符串数组里的所有元素的长度是否和某个给定的整数数组相对应
val a = Array("a", "b", "ac")
val b = Array(1, 1, 2)
//对每个元素进行对比
println(a.corresponds(b)(_.length == _))
9 不使用柯里化实现corresponds。然后尝试从前一个练习的代码来调用。你遇到了什么问题?
没有柯里化则不能使用前一个练习里的代码方式来调用
10 实现一个unless控制抽象,工作机制类似if,但条件是反过来的。第一个参数需要是换名调用的参数吗?你需要柯里化吗?
def r(unless: => Boolean)(x: Int) {
if (unless) {
// 要执行的语句
}
}