<Zhuuu_ZZ > Scala higher order function

Nested function

Two level nesting

  • Requirement: input a string, judge the length of the string and the size of 5, and output two different results respectively
object Test1 {
  def main(args: Array[String]): Unit = {
    //The first method: judge first and then build-in function
//    def fun(s: String): (Int, Int) => Int = {
//      if (s.length > 5) {
//        def add(a: Int, b: Int): Int = {
//          a + b
//        }
//        add
//      } else if (s.length == 5) {
//        (a: Int, b: Int) => a - b
//      } else {
//        _ * _
//      }
// println(fun("hahah")(9, 1))
    
    //The second method: first build-in function and then judge. Based on the built-in function used, it is a structure
      def fun(s:String):(Int,Int)=>Int={
      def suanfa(a:Int,b:Int):Int={
       if(s.length>5)a+b
       else if(s.length==5) a-b
       else a*b
}
      suanfa
    }
    println(fun("hahahf")(5,3))
  }
}

Three layer nesting

  • Requirement: enter the relationship between a number judgment and 3 remainder. If it is equal to zero, enter the sum of two numbers and then judge the size of the sum and 4000. Finally, enter a person's name and output a sentence. On the contrary, enter the difference judgment of two numbers and the size of 1000, and then enter a person's name and output a sentence.
object Test2 {
  def main(args: Array[String]): Unit = {
    def fun(num:Int):(Int,Int)=>String=>Unit={//Nesting is actually the arrow of the output return function. On the left is the input parameter type of the inner function, and on the right is the output parameter type of the memory function
      if(num%3==0){
        def fun2(a:Int,b:Int):String=>Unit={//Why is String here? Because the next function inputs the person's name
          if(a+b>4000){
            def fun3(s:String):Unit={
              println(s+"Congratulations on your high income")
            }
            fun3
          }else{
            def fun3(s:String):Unit={
              println(s+"More efforts are needed")
            }
            fun3
          }
        }
        fun2
      }else{
        def fun2(a:Int,b:Int):String=>Unit={
          if(a-b>1000){
            def fun3(s:String):Unit={
              println(s+"You are so frugal!!!")
            }
            fun3
          }else{
            def fun3(s:String):Unit={
              println(s+"Save some money")
            }
            fun3
          }
        }
        fun2
      }
    }
   fun(2)(5000,3000)("Vest")

The formal parameter is a function and the return is a function

  • **Requirements: * * the input parameters are function and String value. Judge the relationship between this value and 3 remainder and output an addition and subtraction function
object Test3 {
  def main(args: Array[String]): Unit = {
def fun(f:String=>Int,str:String):(Int,Int)=>Int={
  val num=f(str)
  if(num%3==0){
    def fun1(a:Int,b:Int):Int={
      a+b
    }
    fun1
  }else{
    _-_
  }
}
    println(fun((x:String)=>{
      if(x.length>5) 6
      else 1
    }
      ,"hahah")(3,3))
  }
}

Function coritization

  • Coriolism refers to A function that takes function A as A parameter and can return A new function after running. And this new function can handle the remaining parameters of function A.
object Test4 {
  def main(args: Array[String]): Unit = {
    def fun(a:Int,b:Int,c:Int,d:Int):Int={
      a+b+c+d
    }
    def fun1(a:Int,b:Int,c:Int)(d:Int):Int={
      a+b+c+d
    }
    def fun2(a:Int,b:Int)(c:Int,d:Int):Int={
      a+b+c+d
    }
    def fun3(a:Int)(b:Int)(c:Int)(d:Int):Int={
      a+b+c+d
    }
    def fun4(a:Int)(b:Int,c:Int,d:Int):Int={
      a+b+c+d
    }
    println(fun(1,2,3,4))
   println(fun1(1,2,3)(4))
    println(fun2(1,2)(3,4))
    println(fun3(1)(2)(3)(4))
  }
}

pattern matching

  • Requirement: input a number and convert it into corresponding English and judge the type of input
object demoMatch {
  //java class method
  def method1(x:Int):String={
    if(x==1) "one"
    else if(x==2) "two"
    else  "many"
  }
  //pattern matching
  def match1(x:Int):String=x match{
    case 1=>"one"
    case 2=>"two"
    case _=>"many"
  }
//Determine the type of input
  def match2(x:Any):Unit=x match{
    case 1=>println("The value entered is"+x)
    case x:Int=>println("The value entered is Int Type, value:"+x)
    case x:String=>println("The value entered is String Type, value:"+x)
    case x:Double=>println("The value entered is Double Type, value:"+x)
    case _=>println("I don't know what it is")
  }

  def main(args: Array[String]): Unit = {
    println(method1(3))
    println(match1(4))
    match2('a')
  }
}

Sample class

  • First, you need case class to define an object with attributes and types.
  • Then the input parameter type is the object, which is itself a class
  • Then use pattern matching to solve the problem
  • For the sample class, as long as the values are the same, it is the same object, so = = and equals is the same
object demoCaseClass {
  case class Student(name: String, age: Int)
  def match1(studnet: Student): Unit = studnet match {
    case Student("Zhu", 22) => println("Hello," + studnet.name)
    case Student("Tang", 21) => println("Welcome," + studnet.name)
    case stu: Student => println("Your name is:" + stu.name)
  }
  def main(args: Array[String]): Unit = {
   val stu1=Student("zhu",22)
    match1(stu1)
    
    val stu2=Student("Zhu",22)
    if(stu1.equals(stu2)) println("It's the same student")
    else println("No")
    if(stu1==stu2) println("It's really a person")
    else println("How can I tell you they're twins")
  }
}

Implicit parameter

  • Implicit parameters need to be defined in object, not in pure class.
  • And there can only be one in the same type
  • Implicit parameters can only be placed last
  • If there are multiple implicit functions in a function, put them together and there is only one implicit in front of them
  • Priority: pass parameter > implicit parameter > Default
  • The purpose of giving a default value to an implicit parameter is to prevent the error that the value cannot be found due to neither passing parameters nor defining implicit parameters or invalidation.
object demoImplicit {
  def main(args: Array[String]): Unit = {

    def fun1(a:Int,b:Int)(c:Int):Int={ //Coriolis function
    a+b+c
    }
    //Implicit parameters need to be defined in object, not in pure class.
    implicit var a:Int=10 //There can only be one of the same type
    implicit var str:String="hello"
    def fun2(a:Int,b:Int)(implicit c:Int=5):Int={//The purpose of giving a default value to an implicit parameter is to prevent the error that the value cannot be found due to neither passing parameters nor defining implicit parameters or invalidation.
      a+b+c
    }

    def fun3(a:Int,b:Int)(implicit c:Int=5,str:String):Int={//If there are multiple implicit functions in a function, put them together and there is only one implicit in front of them
      println(str)
      a+b+c
    }
    println("fun3 The result is:"+fun3(30,20))//hello
                                       // 60
    println("fun3 The result is:"+fun3(30,30)(20,"heheda"))//heheda
                                                   //  80

    println("fun1 result"+fun1(10,10)(20)) //40
    //Priority: pass parameter > implicit parameter > Default
    println("fun2 result"+fun2(10,10)(20))//40, highest priority
    println("fun2 Fruit grafting"+fun2(10,10)())//25. If there are parentheses, it means that the parameter has been displayed, and the implicit parameter is shielded. However, if it is empty, it can only call the default value of 5. At this time, if you don't even write the default value of 5, you will compile and report an error.
    println("fun2 result"+fun2(10,10))//30. Implicit parameters. Second, the default value takes effect only after the implicit parameters are marked out

  }
}

Tags: Scala Functional Programming

Posted by coreyphp on Wed, 11 May 2022 01:05:44 +0300