zoukankan      html  css  js  c++  java
  • Scala高阶函数

    1、高阶函数的定义:一个函数的返回值或者参数是一个函数,这样的函数就称作高阶函数

    object Fraction {
    
      def main(args: Array[String]): Unit = {
        val f = add _;//这里的f是一个函数,将函数赋值给一个变量
        //这里的f是一个函数类型的变量
        //这里的下划线表示取出函数本身
        val result =  f(1,3);
        println(result);
      }
      def add(a:Int,b:Int) = a+b;
    }
    

    2、以数据为主体,传递函数,批量处理每一个元素

    
        def multi(n:Int) = {n * 3}
    
        val f = multi _;
    
        //通过map将函数变量f传递 将数组的每一个元素都乘以3
        val arr =  Array(1,2,3).map(f);
        for(i<-arr){println(i)}

    3、匿名函数:没有函数名

    val f = (n:Int) => n * 3;
         val arr =  Array(1,2,3).map(f);
        for(i <- arr ) println(i);

    另外一种简单的写法是在map直接写一个匿名函数
    ,不用再通过函数变量传递

      val arr = Array(12,3,4).map((n:Int)=>n*3);//直接再map里面定义一个匿名函数
        for(i<-arr)println(i);

    4、高阶函数的举例

    object Fraction {
    
      def main(args: Array[String]): Unit = {
        println( fun(1,2,f1,f2));
    
      }
    
      //函数的参数是函数
      def fun(a:Int,b:Int,f1:(Int,Int)=>Int,f2:(Int,Int)=>Int)={
        if(a > 0 || a == 0)  f1;
        if(a < 0) f2;
      }
    
      def f1(a:Int,b:Int):Int = a + b;
      def f2(a:Int,b:Int):Int = a - b;
    }
    

    5、这里写图片描述

    欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
  • 相关阅读:
    Django的中间件
    电脑端调手机端
    计算两个时间戳之间相差的时间
    去除html标签 php
    Tp5 一次修改多个数据update
    ThinkPhp5.0 引入全局自定义函数global
    layer 使用教程
    phpstrom 汉化
    phpcms 电脑手机合并
    vue 中 v-model
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10327097.html
Copyright © 2011-2022 走看看