• [scala] scala 函数 (⑦)


    1.scala 函数定义

    2.scala 高阶函数

    3.匿名函数

    4.柯里化

    import scala.math._
    
    /**
      * @author xwolf
      * @date 2017-04-24 9:57
      * @since 1.8
      */
    class Function {
       // _ 将round 方法转化为函数
       val  cel = round _
    
       def add(x:Int,y:Int) = x+y
    
       //函数
       def f(x : => Int) = x.+(3)
    
       def m (r : => Double) = {
          val rs=(Math.PI*r*r*0.5)
          rs}
    
       //高阶函数
       def a(s:(Int)=>Int,z:Int)= s(z)+this.f(z)
    
       //匿名函数定义
       val minus = (m:Int) => m-1
    
       // 柯里化函数定义
       def ads(x:Int)=(y:Int) => x*y
    
       //阶乘 (递归实现)
       def sm(x:Int):BigInt={
          if (x==1 || x==0) 1
          else sm(x-1)*x
       }
    
       //阶乘 (reduceLeft 实现)
       def rsm(x:Int):BigInt={
          (1 to x).reduceLeft(_ * _)
       }
    
       // 求数组的最大值
       def max(ary :Array[Int]):Int={
          ary.reduceLeft(_ max _)
       }
    
       // 求数组的最大值
       def getMax(ary :Array[Int]):Int={
          //底层也是reduceLeft
          ary.max
       }
    }
    

    测试:

    object FunctionTest {
    
      def main(args: Array[String]): Unit = {
    
        val function = new Function
        val cel = function.cel(32)
        println(cel)
        val a = function.f(1)
        println(a)
        val b = function.add(12,32)
        println(b)
        val c = function.m(2.4)
        println(c)
    
        val d = function.minus(3)
        println(d)
        //柯里化
        val e = function.ads(2)(10)
        println(e)
    
        val f = function.sm(5)
        println(f)
    
        val f2 = function.rsm(5)
        println(f2)
    
        val ary =Array(3,32,4,2,2)
        val g =function.getMax(ary)
        println(g)
    
        //高阶函数使用
        val af = function.a(a=>4,3)
        print(af)
      }
    
    }
    

      

      

  • 相关阅读:
    LCA + 二分(倍增)
    Educational Codeforces Round 5
    BNU 51276
    POJ 1511
    hdu2121
    最小树形图(朱刘算法)
    Educational Codeforces Round 1(D. Igor In the Museum) (BFS+离线访问)
    Educational Codeforces Round 1(C. Nearest vectors)
    POJ-2785 4 Values whose Sum is 0(折半枚举 sort + 二分)
    POJ 1661Help Jimmy(逆向DP Or 记忆化搜索 Or 最短路径)
  • 原文地址:https://www.cnblogs.com/lonelywolfmoutain/p/6761048.html
Copyright © 2020-2023  润新知