Scala高阶函数编程--实例演示

本文介绍了Scala中如何通过`arrayOperation`函数结合匿名函数进行集合操作,包括加一和元素翻倍示例。同时展示了函数柯里化的练习,涉及高阶函数和类型推导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

object Test07_Practice_CollectionOperation {
  def main(args: Array[String]): Unit = {
        def arrayOperation(array: Array[Int], op: Int => Int): Array[Int] = {
          for (elem <- array) yield op(elem)
        }

        //定义一个加一操作
        def addOne(elem: Int): Int = {
          elem + 1
        }

        //调用函数
        val newArray: Array[Int] = arrayOperation(arr,add)


        //传入匿名函数,实现元素翻倍
        val newArray2 = arrayOperation(arr, _ * 2)
        println(newArray.mkString(","))

  }
}
  def main(args: Array[String]): Unit = {
    //练习1
    val fun = (i: Int, s: String, c: Char) => {
      if (i == 0 && s == "" && c == '0') false else true
    }
    println(fun(0, "", '0'))
    println(fun(32, "12", 'l'))

    //2.练习2
    def func(i: Int): String => (Char => Boolean) = {
      def f1(s: String): Char => Boolean = {
        def f2(c: Char): Boolean = { //先确定f2的类型, 再确定f1的类型,最后确定func的返回值类型
          if (i == 0 && s == "" && c == '0') false else true
        }

        f2
      }

      f1 //返回值
    }

    println(func(0)("")('0')) //然后根据调用函数顺序来打印
    //简写
        def func(i:Int):String=>(Char=>Boolean)={//定义的类型顺序从第二个函数开始
          s=>{c=>{if (i == 0 && s == "" && c=='0')false else true
            }
          }
        }
        println(func(0)("")('0'))//然后根据调用函数顺序来打印
         def func(i:Int)(s:String)(c:Char):Boolean={if (i == 0 && s == "" && c=='0')false else true//直接定义每个参数的类型,然后使用方法 柯里化
    }
        println(func(4)("")('0'))
  }
}

在这里插入图片描述

  //    println(fact(5))
    println(tailFact(5))
    //  }
    //  //递归实现计算阶乘
    //  def fact(n:Int):Int={
    //    if (n==0)
    //      return 1
    //    fact(n-1) * n//前一项覆盖后一项,直到它为1
    //  }
    //  //尾递归实现

    def tailFact(n: Int): Int = {
      @tailrec
      def loop(n: Int, currRes: Int): Int = {
        if (n == 0) return currRes
        loop(n - 1, currRes * n) //1*5*4*3*2  表达式
      }

      loop(n, 1) //返回值  定义值
      //    println(fact(5)) //计算5的阶乘
      //
      //    def fact(n: Int): Int = {
      //      if (n == 0) return 1
      //      fact(n - 1) * n
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚风时亦鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值