scala function with function parameter

  def main(args:Array[String])
  {
    val v = (x:Int,y:Int)=> {
      if (x >10)
        x+y
      else
        x*y
    }
    println(v(3,4))
    println(anonyMouseFun(3)(5))
    
    println(afun(4)(5))
    def afun(x:Int) = (a:Int) => v(2,3)*a*x
    
    println(bfun(4)(5))
    def bfun(x:Int) = (b:Int) => {
      var fr = v(2,3)
      var fl=fr*b*x
      println(s"fl=$fl")
      (fl*2 + 10) / 50
    }
  }
 
  def anonyMouseFun(x:Int) = (a:Int)=>x*a

print result:

12
15
120
fl=120
5

The above experiments mainly learn to return anonymous functions as the return value of functions. How to practice passing function parameters to a function? See the code below:

def main(args:Array[String])
  {
    val v = (x:Int,y:Int)=> {
      if (x >10)
        x+y
      else
        x*y
    }
    println(v(3,4))
    println(anonyMouseFun(3)(5))
    
    println(afun(4)(5))
    def afun(x:Int) = (a:Int) => v(2,3)*a*x
    
    println(bfun(4)(5))
    def bfun(x:Int) = (b:Int) => {
      var fr = v(2,3)
      var fl=fr*b*x
      println(s"fl=$fl")
      (fl*2 + 10) / 50
    }
    
    println(anonyMouseFun3(itoi))
    def itoi(x:Int) = x+5
    def anonyMouseFun3(f:(Int)=>Int):Int = {
      val av = f(v(3,4))
      av*5+10
    }
    
    println(anonyMouseFun2(itoi))
  }
 
  def anonyMouseFun(x:Int) = (a:Int)=>x*a
 
  def anonyMouseFun2(f:(Int)=>Int):Int = {
    val av = f(3)
    av*5+10
  }

print result:

12
15
120
fl=120
5
95
50

In addition, a phenomenon was also found:

import scala.math._

    val num = 3.14
    val fun = ceil

出现错误提示:missing argument list for method ceil in package math Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing ceil _or ceil(_) instead of ceil.

If you replace it with val fun=ceil _, the compilation will be successful, and what is the principle of printing the result as 4.0?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325153847&siteId=291194637
Recommended