高阶函数应用

来源:互联网 发布:小孩初学英语软件 编辑:程序博客网 时间:2024/05/16 07:25
packagecom.jn.scala.scalalearn

/**
* 求平方根 迭代算法
* Created by jiangning on 2016/1/9.
*/

objectSqrtTest {
 
/**
   *
   *
@param a算法的初始值或称高效能预测值
   *
@param b需要求平方的数字
   *
@return
  
*/
 
def sqrt(a:Double,b:Double):Double={
   
val next = (a+b/a)/2
   
sqrt(next,b)
    next
  }
 
//  在写好上面的方法后发现会是无限循环,即死循环
  //  第一次改进:对上面的方法进行改进,什么时候跳出循环,进行科里化
 
def sqrt2(a:Double)(b:Double):Double={
   
val next = (a+b/a)/2
   
if(b-next * next >0.001|| next*next-b >0.001)sqrt2(next)(b)
    next
}
 
valone=sqrt2(1) _
 
valm=one(2)
//  第二次改进,进行柯里化,定义第一个参数为函数,第二个参数为Double类型,
//  第三个函数为Double
defSQ(f:(Double,Double) => Double)(a:Double)(b:Double):Double={
 
valnext = f(a,b)//这里可以定义求平方根,也可以定义求别的函数
 
if(b-next * next >0.001|| next*next-b >0.001)SQ(f)(next)(b)
  next
}
//定义函数
 
def f(a:Double,b:Double)={
    (a+b/a)/
2
 
}
 
valone2=SQ(f)(1)_
 
valm2=one2(2)


//  第三次改进
//  去掉返回值,因为这里返回的是函数,所以不用定义返回值,将函数进行修改
//  函数(f:(Double) => Double)、变量、预测值a:Double进行分离
 
def SQ2(f:(Double) => Double)(a:Double)={
   
def inSQ(guess:Double):Double={
     
val next = f(guess)//
     
if (accuracy(guess,next)) inSQ(next)
      next
    }
    inSQ(a)
  }

 
//定义函数
 
def two(b:Double)=SQ2(a=>(a+b/a)/2)(1)

 
//判断语句定义函数
//  def accuracy(b:Double,next:Double) = (b-next * next > 0.001 || next*next-b > 0.001)
 
def accuracy(guess:Double,next:Double) = (guess-next >0.001)

 
valm3=two(2)

 
defmain(args: Array[String]) {
//    println(m)
//    println(m2)
   
println(m3)
  }
}
0 0
原创粉丝点击