第5节:Scala函数式编程

来源:互联网 发布:抗韩中年人淘宝店网址 编辑:程序博客网 时间:2024/06/05 00:11




谓顺序





可变参数加上递归的方式实现累加,tail返回的是Seq类型,tail后面转变成可变参数


 

 

 

 

package com.dt.spark.scala.bascis

object HelloFunctionPograming {
  def main(args: Array[String]): Unit = {
  val age=helloword("spark", 80)
  println(age)
//  println("===========    "+fab(100))
  helloword("spark")
  helloword(age=31,name = "hadoop")
  println("==========   "+sum(1,2,3,4,5,6))
   println("==========   "+sum(1 to 6 : _*))
     println("===sumrecursive==="+  sumrecursive(1 to 6 : _*))
  } 
  
  def helloword (name:String,age:Int =30) =  {
     println("hello,my name is " + name +age)
    //ages
     100
  }
  
  
  def fab(n:Long):Long ={
    if (n <=1) 1
    else fab(n-2) + fab(n-1)
  }
  //可变参数,变长参数
  def sum (numbers:Int  * )={
    var result =0 
    for (number <- numbers) result +=number
    result
  }
  
  def sumrecursive(numbers:Int*):Int={
    if (0 == numbers.length) 0
    else numbers.head + sumrecursive(numbers.tail:_*)
  }
  
  
}

 

运行结果

hello,my name is spark80
100
hello,my name is spark30
hello,my name is hadoop31
==========   21
==========   21
===sumrecursive===21

 

 



原创粉丝点击