Scala functional programming advanced partial functions, anonymous functions, higher-order functions, closures

Partial function

Partial functions specifically implement filtering + operations on collection elements.
Implementation requirements: Add +1 to the int type in the collection List(1,2,3,4,"abc") and add it to the new collection, and discard the five implementation methods for other types of elements
.

def test: Unit ={
    
    
    val list =List(1,2,3,4,"abc");
    //实现对 list 中int类型 进行 +1操作 并返回新的数组
    //实现方式1  filter+map
    println("方式1:"+list.filter(f1).map(f3).map(f2));
    //实现方式2  模式匹配
    println("方式2:"+list.map(addOne))

    //以上两种方式 都不够简洁
    //方式3 偏函数
    //偏函数中定义两个方法 isDefinedAt 和 apply方法
    //执行过程 1.遍历集合中的元素
    // 2.调用parFun的isDefinedAt 方法 如果该方法返回为true 则 调用 apply方法  并将新元素添加到一个新的集合
    //定义一个 偏函数 泛型表示 接受 任意类型 返回 Int类型
    val parFun = new PartialFunction[Any,Int] {
    
    
      override def isDefinedAt(x: Any): Boolean = {
    
    
        x.isInstanceOf[Int]
      }
      override def apply(x: Any) = {
    
    
        x.asInstanceOf[Int]+1
      }
    }
    //对集合执行偏函数
    println("方式3:"+list.collect(parFun))

    //偏函数简写形式
    //简写成一个对象的形式
    def parFun2:PartialFunction[Any,Int] = {
    
    
      case in:Int =>in+1
      case d:Double =>d.toInt
    }
    //对集合执行偏函数
    println("方式4:"+list.collect(parFun2))
    //偏函数简写形式2
    //简写成一个对象的形式

    //对集合执行偏函数
    println("方式5:"+list.collect{
    
    
      case in:Int =>in+1
      case d:Double =>d.toInt
    })

  }
  def f1(n:Any):Boolean={
    
    
  n.isInstanceOf[Int]
  }
  def f2(n:Int):Int={
    
    
    n+1
  }
  def f3(n:Any):Int={
    
    
    n.asInstanceOf[Int]
  }
  def addOne(n:Any):Any={
    
    
     n match{
    
    
      case x:Int =>x+1
      case _ =>
    }
  }

Note
1) The map function does not support partial functions, because the bottom layer of the map is to traverse loops and cannot filter elements
2) The collect function supports partial functions

Anonymous function

A function without a name is an anonymous function, and an anonymous function example can be set through a function expression

  def test: Unit ={
    
    
     val triple= (x:Double)=>{
    
    
       3*x
     }
    println(triple);
    println(triple(3));
  }

Higher order function

A function that can accept a function as a parameter is called a higher-order function
example

def test: Unit ={
    
    
      //定义test1 方法 接受两个方法f   f2  和一个 double类型参数
      def test1(f:Double=>Double,f2:Double=>Int,n1:Double)={
    
    
        f(f2(n1))
      }
      def sum(d:Double):Double= d+d
      def mod(d:Double):Int = d.toInt%2
      println(test1(sum,mod,3))

      //高阶函数可以返回一个函数
      def minusxy(x:Int)={
    
    
        (y:Int)=>x-y
      }
      //分步调用 先调用 minusxy(3) 返回一个函数f1 逻辑为 3-y   再调用 f1(4) 返回 3-4 =-1
       val f1 = minusxy(3);
      println(f1(4)); //-1

    //一步到位调用
    println(minusxy(3)(4)) //-1
     print(f1)

  }

Parameter inference and abbreviation

In some cases, the parameter type can be inferred. For example, the function parameter type in the List(1,2,3).map() map can be inferred. In
this case, the corresponding abbreviation can be used.
1) The parameter type can be omitted when the parameter type can be inferred.
2) The parentheses can be omitted when the passed function has only a single parameter.
3) If the variable appears only once on the right side of =>, you can use _ instead of the
example

def test: Unit ={
    
    
    val list = List(1,2,3,4)
    println(list.map((x:Int)=>x+1))//传入一个匿名函数
    println(list.map((x)=>x+1))//省略参数类型
    println(list.map(x=>x+1))//只有一个参数可以省略括号
    println(list.map(_+1))//参数在右侧只出现一次可以使用 _代替
    println("---------------------------------")
    println(list.reduce(f1))//常规函数写法
    println(list.reduce((n1:Int,n2:Int)=>n1+n2))//匿名函数写法
    println(list.reduce((n1,n2)=>n1+n2))
    //println(list.reduce(n1,n2=>n1+n2))参数数量大于1不能省略参数括号
    println(list.reduce(_+_))//参数在右侧只出现一次可以使用 _代替
  }
  def f1(n1:Int,n2:Int): Int ={
    
    
    n1+n2
  }

Closure

A closure is an overall example of a function and its related reference environment.

  def minusxy(x: Int) = (y: Int) => x - y
    val f = minusxy(10)
    println(f(8))

Explain that
minusxy returns an anonymous function (y: Int) => x-y, the function refers to the variable x outside the function, so x and the anonymous function
form an associated whole, that is, a closure.
val f = minusxy(10) The function f is a closure, and xd= is 10 every time you call f

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/107989869