美文网首页
2020-11.05-Scala-25(高阶函数练习题)

2020-11.05-Scala-25(高阶函数练习题)

作者: 冰菓_ | 来源:发表于2020-11-07 12:26 被阅读0次

1.案例一

  1. 编写函数values(fun: (Int) => Int, low: Int, high: Int),该函数输出一个集合,对应给定区间内给定函数的输入和输出。比如,values(x => x * x, -5, 5)应该产出一个对偶的集合(-5, 25), (-4, 16), (-3, 9), …, (5, 25)
def main(args: Array[String]): Unit = {
       //不需要告知类型,使用类型推断
       val value = function0(x => x * x, -5, 5)
       println(value)


  }
  //1.理解题意
  def  function0(f:Int=>Int,low: Int, high: Int)={
             //创建一个可变集合
      var array = ListBuffer[(Int,Int)]()
      low to high foreach(data=>
          //归纳  += :+  适用场合
           array.append( (data ,f(data)))
         )
         array
  }

案例二

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

  def main(args: Array[String]): Unit = {
       var array = Array(1,2,3,4,5,6,7,88,100,123,14444)
       println(array.reduceLeft(function1))


  }
  //使用泛型表示
   def function1[S,T](num:S,num2:T)={
           if(num.toString.toInt.isInstanceOf[Int] && num2.toString.toInt.isInstanceOf[Int]){
           if(num.toString.toInt > num2.toString.toInt )  num  else  num2}
           else  throw new  Exception
   }

案例三

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

  def main(args: Array[String]): Unit = {
    println(function3(12))


  }
  
   def function3(num :Int)={
       if(num<= 0) {throw  new Exception}
       (1 to num ).reduceLeft(_ * _)
   }

案例四

编写函数largest(fun: (Int) => Int, inputs: Seq[Int]),输出在给定输入序列中给定函数的最大值。举例来说,largest(x => 10 * x - x * x, 1 to 10)应该返回25。不得使用循环或递归

方法一

  def main(args: Array[String]): Unit = {
      println(function4(x => 10 * x - x * x, 1 to 10))
  }
   def function4(f:Int=>Int,inputs:Seq[Int])={
         //考虑使用一个变量接收这个最大值
         var max =0;
        for(index<-inputs){
            if(max < f(index))  max = f(index)
        }
        max
   }

方法二

def main(args: Array[String]): Unit = {
      println(function5(x => 10 * x - x * x, 1 to 10))
  }
  
   def function5(f:Int=>Int,inputs:Seq[Int])={
          inputs.map(f).max
   }

案例五

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

方法一

  def main(args: Array[String]): Unit = {
          println(function6(x => 10 * x - x * x, 1 to 10))
  }

  def function6(f: Int => Int, inputs: Seq[Int]) = {
    //考虑使用元组,元组实现了(k,v)形式k相当于索引
    var result = inputs.map(data => (data, f(data)))
      .reduce((data1, data2) =>
        if (data1._2 < data2._2) data2 else data1
      )
    result._1
  }

方法二:实现一种简洁的写法!!!!! ----我竟然没有意识到

  def main(args: Array[String]): Unit = {
          println(function6(x => 10 * x - x * x, 1 to 10))
  }

  def function6(f: Int => Int, inputs: Seq[Int]) = {
    //考虑使用元组,元组实现了(k,v)形式k相当于索引
    inputs.map(data => (data, f(data)))
      .reduce((data1, data2) =>
        if (data1._2 < data2._2) data2 else data1
      )._1
  }

案例六(反思偏函数和高阶函数之间的区别)

要得到一个序列的对偶很容易,比如:
val pairs = (1 to 10) zip (11 to 20)
假定你想要对这个序列做某种操作,比如,给对偶中的值求和,但是你不能直接使用:
pairs.map( + )
函数 _ + _ 接受两个Int作为参数,而不是(Int, Int)对偶。编写函数adjustToPair,该函数接受一个类型为(Int, Int) => Int的函数作为参数,并返回一个等效的, 可以以对偶作为参数的函数。举例来说就是:adjustToPair(_ * _)((6, 7))应得到42。然后用这个函数通过map计算出各个对偶的元素之和

  def main(args: Array[String]): Unit = {
    println(function7(_ * _)(6, 7))
    println(function7(_ + _)(6, 7))
    //考虑
    val pairs = (1 to 10) zip (11 to 20)
    println(pairs.map(function7(_ * _)))
    
  }

  def function7(f: (Int, Int) => Int) = {
    //反思这两种写法的区别
    (x: (Int, Int)) => f(x._1, x._2)
    // (data: Int, data1: Int) => f(data, data1)
  }

案例七(控制抽象简单练习,考虑要柯里化)

实现 if unless的功能

  //抽象控制模拟if 和 unless
  def main(args: Array[String]): Unit = {
        //实现if
        var a =10
        fun(a>0){
            a-=1
            println(a)
        }

    // unless
    fun1(0 < 1){
        println(10)
    }


  }
  //注意把any 类型 转换 为 unit
  def fun (f: => Boolean)(f1: =>Unit):Unit={
        if (f){
            f1
          fun(f)(f1)
        }
  }
  def fun1 (f: => Boolean)(f1: =>Unit):Unit={
    if (f){
      f1
    }
  }

案例八(柯里化 解耦,一个简单的练习)

两个字符串,先转大写 然后比较大小,考虑步骤分离
发现一个问题,big函数有两种写法,有什么区别

object Test2 {
  def main(args: Array[String]): Unit = {
    //
    println("hh".big("Hh", eq))
    println("hh".big("Hh", _.equals(_)))
    println("hh".big1("Hh")(eq))
    println("hh".big1("Hh")(_.equals(_)))


  }
   def eq(string1: String,string2: String)={
           string1.equals(string2)
   }


  implicit class fun(s1: String) {
    def big(s2: String, f: (String, String) => Boolean) = {
         f(s1.toUpperCase,s2.toUpperCase)
    }
  }
  implicit class fun2(s1: String) {
    def big1(s2: String)( f: (String, String) => Boolean) = {
      f(s1.toUpperCase,s2.toUpperCase)
    }
  }
}

案例九Word(Count案例,理解foldleft第一个参数的意义)

统计字符串字母出现的次数.

object Test3 {
  def main(args: Array[String]): Unit = {
    var st = "AAAABBBBCCCCWWWJJJTTDDDDEEE"
    //用可变map和不可变map分别实现
    // Map[Char, Int]()  ..这里要加()...这里map是不会初始化的最左边总有一个map
    val value = st.foldLeft(Map[Char, Int]())(MyfoldLeft)
    println(value)
    //HashMap(E -> 3, T -> 2, J -> 3, A -> 4, B -> 4, C -> 4, W -> 3, D -> 4)
    var map =  mutable.Map[Char, Int]()
    val value1 = st.foldLeft(map)(MyfoldLeft1)
    //HashMap(A -> 4, B -> 4, C -> 4, D -> 4, T -> 2, E -> 3, W -> 3, J -> 3)
    println(value1)
  }
  def MyfoldLeft(map: Map[Char, Int], char: Char) = {
    //如果没有这个字母就+1 考虑使用getorelse
    map + (char -> (map.getOrElse(char, 0) + 1))
  }
  def MyfoldLeft1(map: mutable.Map[Char, Int], char: Char) = {
    //如果没有这个字母就+1 考虑使用getorelse
    map + (char -> (map.getOrElse(char, 0) + 1))
  }
}

相关文章

  • 2020-11.05-Scala-25(高阶函数练习题)

    1.案例一 编写函数values(fun: (Int) => Int, low: Int, high: Int),...

  • 学习笔记

    高阶函数 高阶函数只是将函数作为参数或返回值的函数 练习题map 请把用户输入的不规范的英文名字,变为首字母大写,...

  • python学习(三)函数式编程

    高阶函数 函数也是变量,函数参数为函数的函数,称作高阶函数 自定义高阶函数 内建高阶函数 map/reducema...

  • 11.Lambda和高阶函数(Lambda and Higher

    高阶函数 kotlin_Lambda,高阶函数 *swift_高阶函数

  • Python | 高阶函数基本应用及Decorator装饰器

    一、高阶函数 理解什么是高阶函数?以及高阶函数的基本应用方法 ▲ 高阶函数 在了解什么是高阶函数之前,我们来看几个...

  • 四、函数进阶

    一. 高阶函数 参数类型包含函数类型或返回值类型为函数类型的函数为高阶函数。 常见的高阶函数 高阶函数的调用 二....

  • Kotlin 高阶函数

    什么是高阶函数 将函数作为参数或者返回值的,称高阶函数。 定义高阶函数 action是一个高阶函数,(Int) -...

  • 高阶组件

    高阶组件 先来引入这个概念 高阶函数是什么? 高阶函数就是一个函数返回一个函数eg: 高阶组件 类同 高阶组件就是...

  • [JS函数] (Array)の高阶函数

    JS函数 高阶函数 高阶函数英文叫Higher-order function。那么什么是高阶函数? JavaScr...

  • HOC - High Order Component 高阶组件

    高阶函数 简而言之,可以接收函数作为参数的函数就是一个高阶函数。 上面的hoc函数就是一个高阶函数。 高阶组件 高...

网友评论

      本文标题:2020-11.05-Scala-25(高阶函数练习题)

      本文链接:https://www.haomeiwen.com/subject/aqdkvktx.html