[scala] scala 函数 (⑦)

时间:2023-03-08 22:10:01

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)
} }