第十二章:高阶函数

来源:互联网 发布:java compiler 编辑:程序博客网 时间:2024/05/06 11:54

第十二章:高阶函数

标签(空格分隔): scala课后习题


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): List[(Int,Int)] = {        (low to high) zip {(low to high).map(fun(_))} toList    }

2 如何用reduceLeft得到数组中的最大元素?

def ArrayMaxNumber(arr : Array[Int]):Int={        arr.reduceLeft((a,b)=>if (a>b) a else b)    }

3 用to和reduceLeft实现阶乘函数,不得使用循环或递归

    def jiecheng(num :Int):Int={        (1 to num).reduceLeft(_*_)    }

4 前一个实现需要处理一个特殊情况,即n<1的情况。展示如何用foldLeft来避免这个需要。

def jiecheng(num: Int):Int={    (1 to num).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] )={    inputs.map(fun).max  }

6 修改前一个函数,返回最大的输出对应的输入。举例来说,largestAt(fun:(Int)=>Int,inputs:Seq[Int])应该返回5。不得使用循环或递归

  def largestInput(fun : (Int)=>Int, inputs : Seq[Int] )={    inputs.reduceLeft((a,b)=>if (fun(a) > fun(b)) a else b)  }

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 adjustToPair(func:(Int,Int)=>Int):((Int,Int))=>Int={    (tuple:(Int,Int)) => func(tuple._1,tuple._2)  }

8 在12.8节中,你看到了用于两组字符串数组的corresponds方法。做出一个对该方法的调用,让它帮我们判断某个字符串数组里的所有元素的长度是否和某个给定的整数数组相对应

def compareArrayLength(srcArr : Array[String], compareLengh : Array[Int]):Boolean={    arr1.corresponds(arr2)(_.length == _)  }  val arr1 = Array("Hello","world","scala is funny")  val arr2 = Array(5,5,14)  println(compareArrayLength(arr1,arr2))

10 实现一个unless控制抽象,工作机制类似if,但条件是反过来的。第一个参数需要是换名调用的参数吗?你需要柯里化吗?

  def unless(condition: =>Boolean)(block: =>Unit)={      if(!condition){        block      }  }  var x = 1  unless(x>10){    println(x)    x += 1  }

当然都需要,如果不用换名调用参数的话。代码将会是如下这样:

  def unless(condition:()=>Boolean)(block:()=>Unit)={      if(!condition()){        block()      }  }  var x = 1  unless(()=>x>10){    ()=>      println(x)      x += 1  }

如果不用柯里化的话,就惨不忍睹了。

  def unless(condition:()=>Boolean,block:()=>Unit)={      if(!condition()){        block()      }  }  var x = 1  unless(()=>x>10 , {()=>println(x); x += 1;})

根本就达不到if语句这样的效果。

0 0
原创粉丝点击