代码3.1

scala> :paste		
// Entering paste mode (ctrl-D to finish)
	val str=List("Hello","World")
	for(i<-0 to 1) print(str(i))
	println()
// Exiting paste mode, now interpreting.
HelloWorld
str: List[String] = List(Hello, World)

代码3.2

object HelloWorld {
	/* 第一个Scala程序
	* 它将输出Hello World!
	*/
	def main(args: Array[String]) {
		println("Hello, World!") // 输出 Hello World!
	}
}

代码3.3

//声明一个val变量,Scala会自动类型推断
scala> val TestString="Hello World!"
TestString: String = Hello World!

代码3.4

//声明一个val变量,明确指定变量的类型
scala> val TestString:String="Hello World!"
TestString: String = Hello World!

代码3.5

//String全称是java.lang.String,Scala会默认导入java.lang包
scala> val TestString:java.lang.String="Hello World!"
TestString: String = Hello World!

//打印变量  
scala> println(TestString)
Hello World!

代码3.6

//不能被重新赋值,因为它是val变量  
 scala> TestString="Hello Scala!"
<console>:15: error: reassignment to val
      TestString="Hello Scala!"
          ^

代码3.7

//var声明可变变量
scala> var TestString="Hello Cruel World!"
TestString:String: = Hello Cruel World!

代码3.8

//对var变量重新赋值
scala> TestString="Hello Wonderful World!"
TestString:String: = Hello Wonderful World!

代码3.9

//定义一个类型为Int的变量x
scala>var x=5
x:Int =5

//重新赋一个String值,会导致编译错误。
scala> x="Hello World"
<console>:8:error:type mismatch;
  found   : String("Hello World")
  required : Int
	x="Hello World"
       ^

代码3.10

//定义一个类型为Double的变量y
scala> var y=1.5
y:Double =1.5

//重新赋值一个Int数
scala> y=42
y:Double =42.0

代码3.11

//普通val变量定义
scala> val TestString="Hello Scala"
TestString: String = Hello Scala

//经过lazy关键字修饰的变量在定义时不被赋值
scala> lazy val TestString="Hello Scala"
TestString:String =<lazy>

//在使用时,变量才会赋值
scala> TestString
res0: String= Hello Scala

代码3.12

//不能将lazy关键字用于var变量
scala> lazy var TestString2="Goodbye Scala"
<console>:1:error:lazy not allowed here. Only vals can be lazy
      Lazy var TestString2="Goodbye Scala"

代码3.13

//特殊字符”π”是一个合法的Scala标识符
scala> val π =3.14159
π:Double = 3.14159

//特殊字符”$”是一个合法的Scala标识符
scala> val $ ="USD currency symbol"
$:String = USD currency symbol

//”o_0 ”是一个合法的Scala标识符
scala> val o_0 ="Hmm"
o_0:String =Hmm

//值名”50cent”是不合法的,因为标识符不能以数字开头。在这里,编译器最初会把这个名字解析为一个数字,解析到字母”c”时会出错
scala> val 50cent="$0.50"
<console>:1: error: Invalid literal number
val 50cent="$0.50"
^
//值名”a.b”是不合法的,因为点号不是操作符字符
scala> val a.b=25
<console>:11: error: not found: value a

       val a.b=25
           ^
//加上反引号重写就可以解决问题
scala> val `a.b`=4
a.b: Int = 4

代码3.14

//十六进制定义法
scala> val x=0x29
x:Int =41

//十进制定义法
scala> val y=41
y:Int =41

代码3.15

//要定义Float类型浮点数,需要在浮点数后面加F或f
scala> val floatNumber=3.14159F
floatNumber: Float=3.14159

//小写的f也可以
scala> val floatNumber=3.14159f
floatNumber: Float=3.14159

代码3.16

//Double类型定义,直接输入浮点数,编译器会将其自动推断为Double类型
scala> val doubleNumber=3.14159
doubleNumber:Double=3.14159

代码3.17

//浮点数指数表示法,e也可以是E,0.314159e1与0.314159*10等同
scala> val floatNumber=0.314159e1
floatNumber: Double=3.14159

代码3.18

//字符定义,用' '将字符包裹
scala> var charLiteral='A'
charLiteral:Char=A

代码3.19

//通过转义符\进行双引号的定义
scala> var x='\"'
x:Char = "

//通过使用Unicode编码进行双引号的定义
scala> var y='\u0022'
y:Char = "

代码3.20

//字符串变量用双引号""包裹
scala> val helloWorld="Hello World"
helloWorld:String =Hello World

代码3.21

//要定义"Hello World",可以加入转义符\
scala> val helloWorld2="\"Hello World\""
helloWorld2:String ="Hello World"

代码3.22

//直接定义Boolean类型变量
scala> var x=true
x:Boolean = true

//含逻辑表达式的Boolean类型变量
scala> var y=2>3
y:Boolean = false

代码3.23

//实际上调用了(5).+(3)
scala> val sum1 = 5+3 
sum1: Int = 8

//可以发现,写成方法调用的形式,和上面得到相同的结果
scala> val sum2 = (5).+(3) 
sum2: Int = 8 

代码3.24

//定义整型变量i
scala> var i = 5
i: Int = 5

//将i递增
scala> i += 1    
scala> println(i)
6 

代码3.25

//运算符
scala> var res=3>2
res: Boolean =true

//<=运算符,!为取反操作
scala> res= !(3 <= -3)
res: Boolean = true

代码3.26

//定义Boolean类型变量bool
scala> val bool=true
bool :Boolean = true 

//逻辑与&&,同时为true时才会为true,否则为false
scala> bool && !bool
res0: Boolean = false

//逻辑或||,同时为false时才为false,否则为true
scala> !bool || bool
res1: Boolean = true

//逻辑或||,同时为false时才为false
scala> bool || !bool
res0: Boolean = true

scala> bool || !bool
res1: Boolean = true

scala> false || false
res2: Boolean = false


代码3.27

//Int类型
scala> 1 to 10 by 2
res3: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)  

//Long类型
scala> 1L to 10L by 2
res4: scala.collection.immutable.NumericRange[Long] = NumericRange(1, 3, 5, 7, 9)  

//BigInt类型
scala> BigInt(1) to BigInt(10) by 2
res5: scala.collection.immutable.NumericRange[BigInt] = NumericRange(1, 3, 5, 7, 9)

代码3.28

//Float类型
scala> 0.5f to 5.9f by 0.8f
res7: scala.collection.immutable.NumericRange[Float] = NumericRange(0.5, 1.3, 2.1, 2.8999999, 3.6999998, 4.5, 5.3)  

//Double类型
scala> 0.5 to 5.9 by 0.8
res8: scala.collection.immutable.NumericRange[Double] = NumericRange(0.5, 1.3, 2.1, 2.9000000000000004, 3.7, 4.5, 5.3)

//BigDecimal类型
scala> BigDecimal(0.5) to BigDecimal(5.9) by 0.8
res9: scala.collection.immutable.NumericRange.Inclusive[scala.math.BigDecimal] = NumericRange(0.5, 1.3, 2.1, 2.9, 3.7, 4.5, 5.3)


代码3.29

object Demo {
    def main(args: Array[String]) {
        var x = 10

        if( x < 20 ){
          println("This is if statement")
        }
    }
}

代码3.30

object Demo {
    def main(args: Array[String]) {
        var x = 30
        if( x < 20 ){
          println("This is if statement")
        } else {
          println("This is else statement")
        }
    }
}

代码3.31

object Demo {
    def main(args: Array[String]) {
        var x = 30

        if( x == 10 ){
          println("Value of X is 10")
        } else if( x == 20 ){
          println("Value of X is 20")
        } else if( x == 30 ){
          println("Value of X is 30")
        } else{
          println("This is else statement")
        }
    }
}

代码3.32

object Demo {
    def main(args: Array[String]) {
        var x = 30
        var y = 10
      
        if( x == 30 ){
            if( y == 10 ){
              println("X = 30 and Y = 10")
            }
        }
    }
}

代码3.33

object Demo {
    def main(args: Array[String]) {
 		var  i = 9
 		while (i > 0) {
   			 i -= 3
   		     printf("here is %d\n",i)
 		} 
	}
}

代码3.34

object Demo {
    def main(args: Array[String]) {
 		var  i = 9
 		do{  
             i -= 3;
             printf("here is %d\n",i)
 		   }while (i > 0) 
	}
} 

代码3.35

for (i <- 1 to 5) println("i="+i)

代码3.36

object Demo {
     def main(args: Array[String]) {
          for(i<-1 to 5 if (i>3)){
  			  for(j<-5 to 7 if (j==6)){
      				println("i="+i+",j="+j) 
			  }
		  }
	  }
  }


代码3.37

object Demo {

     def main(args: Array[String]) {
       println(matchTest(3))
     }

     def matchTest(x: Int): String = x match {
      case 1 => "one"
      case 2 => "two"
      case _ => "many"
     }
}

代码3.38

object Demo {
     def main(args: Array[String]) {
        println(matchTest(5))
      }
   
     def matchTest(x: Int): String = x match {
       case 1 => "one"
       case 2 => "two"
       case 3 => "three"
       case unexpected => unexpected + " is Not Allowed"
     }
}


代码3.39

object Demo {
     def main(args: Array[String]) {
        println(matchTest("two"))
        println(matchTest("test"))
        println(matchTest(1))
      }
   
     def matchTest(x: Any): Any = x match {
        case 1 => "one"
        case "two" => 2
        case y: Int => "scala.Int"
        case _ => "many"
     }
}

代码3.40

for (elem <- List(1,2,3,4)){
      elem match {
          case _ if (elem %2 == 0) => println(elem + " is even.")
          case _ => println(elem + " is odd.")
          }
}


代码3.41

object Demo {
    def main(args: Array[String]) {
        val alice = new Person("Alice", 25)
        val bob = new Person("Bob", 32)
        val charlie = new Person("Charlie", 32)
   
        for (person <- List(alice, bob, charlie)) {
           person match {
              case Person("Alice", 25) => println("Hi Alice!")
              case Person("Bob", 32) => println("Hi Bob!")
              case Person(name, age) => println(
                "Age: " + age + " year, name: " + name + "?")
           }
        }
     }
     case class Person(name: String, age: Int)
}

代码3.42

import scala.collection.mutable.ArrayBuffer
object Demo {
    def main(args: Array[String]) {
		//定义动态数组z
		val z=ArrayBuffer[String]()

		//向数组中添加元素
		z+="Zara"
		println(z.length)

		//一次添加多个元素
		z+=("Nuha", "Ayan")
		println(z.length)

		//在数组索引为1地位置插入元素"Amy"
		z.insert(1,"Amy")
		println(z(1))

		//删除索引为2的"Nuha",输出新的索引为2 的元素
		z.remove(2,1)//从索引2开始删除1个元素
		println(z(2))
	}
}


代码3.43

object Demo {
    def main(args: Array[String]) {
         var myList = Array(1.9, 2.9, 3.4, 3.5)

         // 直接数组遍历输出所有元素
         for ( x <- myList ) {
            println( x )
         }

        // 所有元素求和
         var total = 0.0;
      
        //索引遍历所有元素,进行累加操作
        for ( i <- 0 to (myList.length - 1)) {
              total += myList(i)  
 		}

        println("Total is " + total)

        // 索引遍历所有元素,寻找数组最大值
        var max = myList(0)
        for ( i <- 1 to (myList.length - 1) ) {
           if (myList(i) > max) max = myList(i)
        }

        println("Max is " + max);
    }
}


代码3.44

import Array._
object Demo {
    def main(args: Array[String]) {
        var myList1 = Array(1.9, 2.9, 3.4, 3.5)
           
        //生成新的数组myList2
        var myList2 = for(x<-myList1)yield x+1
      
        // 输出所有数组元素
        for ( x <- myList2) {
           println( x )
        }
    }
}

代码3.45

import Array._
object Demo {
   def main(args: Array[String]) {

//使用Range生成数组
      var myList1 = range(10, 20, 2)
      var myList2 = range(10,20)

      // 打印所有数组元素
       for ( x <- myList1 ) {
         print( " " + x )
       }
      println()

       for ( x <- myList2 ) {
         print( " " + x )
       }
   }
}

代码3.46

import Array._
object Demo {
   def main(args: Array[String]) {
       //定义三行三列的整型二维数组
       var myMatrix = ofDim[Int](3,3)

       //给各元素赋值
       for (i <- 0 to 2) {
          for ( j <- 0 to 2) {
              myMatrix(i)(j) = j
          }
       }

	   // 打印二维数组
       for (i <- 0 to 2) {
          for ( j <- 0 to 2) {
             print(" " + myMatrix(i)(j))
           }
          println()
        }
    }
}

代码3.47

//字符串类型List
scala> val fruit: List[String] = List("apples", "oranges", "pears")
fruit: List[String] = List(apples, oranges, pears)

//前一个语句与下面语句等同
scala> val fruit: List[String] = List.apply("apples", "oranges", "pears")
fruit: List[String] = List(apples, oranges, pears)

//数值类型List
scala> val nums: List[Int] = List(1, 2, 3, 4)
nums: List[Int] = List(1, 2, 3, 4)

//多重List,List的子元素为List
scala> val multiDList=List(List(1,2,3),List(4,5,6),List(7,8,9))
multiDList=:List[List[Int]]=List(List(1,2,3),List(4,5,6),List(7,8,9))

//遍历List
scala> for(i<-multiDList)println(i)
List(1,2,3)
List(4,5,6)
List(7,8,9)


代码3.48

//字符串类型List
scala> val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
fruit: List[String] = List(apples, oranges, pears)

//数值类型List
scala> val nums = 1 :: (2 :: (3 :: (4 :: Nil)))
nums: List[Int] = List(1, 2, 3, 4)

// 定义空列表
scala> val empty = Nil
empty: scala.collection.immutable.Nil.type = List()

//多重List,List的子元素为List
scala> :paste
// Entering paste mode (ctrl-D to finish)
val multiDList = (1 :: (2 :: (3 :: Nil))) ::
          		 (4 :: (5 :: (6 :: Nil))) ::
                 (7 :: (8 :: (9 :: Nil))) :: Nil
// Exiting paste mode, now interpreting.
multiDList: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))

代码3.49

object Demo {
    def main(args: Array[String]) {
      
        // 重复元素apples ,3次
        val fruit = List.fill(3)("apples") 
        println( "fruit : " + fruit  )

       //重复元素2 ,10 次 
       val num = List.fill(10)(2)        
       println( "num : " + num)
    }
}


代码3.50

object Demo {
    def main(args: Array[String]) {
        val fruit = "apples" :: ("oranges" :: ("pears" :: Nil))
        val nums = Nil

        //输出List的第一个元素
        println( "Head of fruit : " + fruit.head )

        //输出List的除第一个元素之外的所有元素
        println( "Tail of fruit : " + fruit.tail )

        //判断List是否为空
        println( "Check if fruit is empty : " + fruit.isEmpty )
        println( "Check if nums is empty : " + nums.isEmpty )  
    }
}

代码3.51

object Demo {
    def main(args: Array[String]) {

        //创建List
        val fruit1 = "apples" :: ("oranges" :: ("pears" :: Nil))
        val fruit2 = "mangoes" :: ("banana" :: Nil)

        // 使用 ::: 操作符连接两个或者多个列表    
        var fruit = fruit1 ::: fruit2
        println( "fruit1 ::: fruit2 : " + fruit )
      
        // 使用集合.:::()方法连接两个列表
        fruit = fruit1.:::(fruit2)
        println( "fruit1.:::(fruit2) : " + fruit )

        // 通过两个或多个列表作为参数。
        fruit = List.concat(fruit1, fruit2)
        println( "List.concat(fruit1, fruit2) : " + fruit)
    }
}


代码3.52

//创建集mySet
scala> var mySet = Set("Hadoop","Spark")
mySet: scala.collection.immutable.Set[String] = Set(Hadoop, Spark)  

//向mySet中增加新的元素
scala> mySet += "Scala" 
scala> println(mySet.contains("Scala"))
true

代码3.53

//导入可变集包  
scala> import scala.collection.mutable.Set
import scala.collection.mutable.Set

//定义一个集合,这里使用的是mutable
scala> val myMutableSet = Set("Database","BigData")
myMutableSet: scala.collection.mutable.Set[String] = Set(BigData, Database)

//向集中添加一个元素。
scala> myMutableSet += "Cloud Computing"
res0: myMutableSet.type = Set(BigData, Cloud Computing, Database)

//输出结果
scala> println(myMutableSet)
Set(BigData, Cloud Computing, Database)

代码3.54

object Demo {
    def main(args: Array[String]) {

        //创建Set
        val fruit = Set("apples", "oranges", "pears")
        val nums: Set[Int] = Set()

        //输出Set的第一个元素
        println( "Head of fruit : " + fruit.head )

        //输出Set的除第一个元素之外的所有元素
        println( "Tail of fruit : " + fruit.tail )

        //判断Set是否为空
        println( "Check if fruit is empty : " + fruit.isEmpty )
        println( "Check if nums is empty : " + nums.isEmpty )
    }
}

代码3.55

object Demo {
   def main(args: Array[String]) {

      //创建Set
      val num = Set(5,6,9,20,30,45)

      //在集合中查找最大值与最小值
      println( "Min element in Set(5,6,9,20,30,45) : " + num.min )
      println( "Max element in Set(5,6,9,20,30,45) : " + num.max )
   }
}

代码3.56

object Demo {
   def main(args: Array[String]) {

      //创建Set
      val num1 = Set(5,6,9,20,30,45)
      val num2 = Set(50,60,9,20,35,55)

      // 查找两个集合之间的公共值
      println( "num1.&(num2) : " + num1.&(num2) )
      println( "num1.intersect(num2) : " + num1.intersect(num2) )
   }
}


代码3.57

object Demo {
    def main(args: Array[String]) {

        //创建Set
        val fruit1 = Set("apples", "oranges", "pears")
        val fruit2 = Set("mangoes", "banana","apples")

        // 使用++ 操作符连接两个或多个集合
        var fruit = fruit1 ++ fruit2
        println( "fruit1 ++ fruit2 : " + fruit )

        // 使用 ++ 作为方法连接两个集合
        fruit = fruit1.++(fruit2)
        println( "fruit1.++(fruit2) : " + fruit )
    }
}

代码3.58

//导入Map包
scala> import scala.collection.mutable.Map 
import scala.collection.mutable.Map

//定义可变映射
scala> val colors2 = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
colors2: scala.collection.mutable.Map[String,String] = Map(azure -> #F0FFFF, red -> #FF0000, peru -> #CD853F)

//更改映射键值对
scala> colors2("red" ) = "#9C661F"

//添加映射键值对
scala> colors2("green") ="#00FF00"

//输出映射键值对
scala> for ((k,v) <- colors2) printf("( %s , %s)\n",k,v)
( green , #00FF00)
( azure , #F0FFFF)
( red , #9C661F)
( peru , #CD853F)


代码3.59

//定义一个空映射
scala> var A:Map[Char,Int] = Map()
A: Map[Char,Int] = Map()

//通过运算符+向映射中添加元素
scala> A += ('I' -> 1)
scala> A += ('J' -> 5)
scala> A += ('K' -> 10)
scala> A += ('L' -> 100)

//输出映射的键值对
scala> for ((k,v) <- A) printf("( %s , %d)\n",k,v)
(I,1)
(J,5)
(K,10)
(L,100)

代码3.60

object Demo {
    def main(args: Array[String]) {
  
       //创建映射
        val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
        val nums: Map[Int, Int] = Map()

        //输出映射中的键
        println( "Keys in colors : " + colors.keys )

        //输出映射中的值
        println( "Values in colors : " + colors.values )

        //判断映射是否为空
        println( "Check if colors is empty : " + colors.isEmpty )
        println( "Check if nums is empty : " + nums.isEmpty )
    }
}

代码3.61

object Demo {
  def main(args: Array[String]) {

      //创建映射
      val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")

     //判断映射中是否包含键"red"
      if( colors.contains( "red" )) {
         println("Red key exists with value :"  + colors("red"))
      } else {
           println("Red key does not exist")
      }

     //判断映射中是否包含键"maroon"
     if( colors.contains( "maroon" )) {
         println("Maroon key exists with value :"  + colors("maroon"))
      } else {
         println("Maroon key does not exist")
      }
   }
}

代码3.62

object Demo {
    def main(args: Array[String]) {

        //创建映射
        val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF","peru" ->"#CD853F")
      
        //使用for循环输出键值对
        for ((k,v) <- colors) printf("Color is : %s and the code is: %s\n",k,v)

        //使用foreach输出键值对
        colors.keys.foreach{ i =>  
            print( "Key = " + i )
            println(" Value = " + colors(i) )
        }
    } 
}

代码3.63

object Demo {
    def main(args: Array[String]) {

        //创建映射
        val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
      
        //查找记录
        println("capitals.get( \"France\" ) : " +  capitals.get( "France" ))
        println("capitals.get( \"India\" ) : " +  capitals.get( "India" ))
    }
}


代码3.64

object Demo {
    def main(args: Array[String]) {
      
        //创建映射
        val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
      
        //查找记录的具体值
        println("show(capitals.get( \"Japan\")) : " + show(capitals.get( "Japan")) )
        println("show(capitals.get( \"India\")) : " + show(capitals.get( "India")) )
    }
   
	//定义可选值分离函数
	def show(x: Option[String]) = x match {
		 case Some(s) => s
		 case None => "?"
	}
}

代码3.65

object Demo {
    def main(args: Array[String]) {

        //定义Option
        val a:Option[Int] = Some(5)
        val b:Option[Int] = None 
      
		//设置没有值时默认为0
        println("a.getOrElse(0): " + a.getOrElse(0) )
      
		//设置没有值时默认为10
        println("b.getOrElse(10): " + b.getOrElse(10) )
    }
}

代码3.66

object Demo {
    def main(args: Array[String]) {

        //定义Option
        val a:Option[Int] = Some(5)
        val b:Option[Int] = None 
      
       //判断Option是否为空
        println("a.isEmpty: " + a.isEmpty )
        println("b.isEmpty: " + b.isEmpty )
   }
}


代码3.67

object Demo {
     def main(args: Array[String]) {

          //创建迭代器
		  val iter = Iterator("Hadoop","Spark","Scala")

          //循环输出迭代器指向对象中的所有元素
          while (iter.hasNext) {
    			 println(iter.next())
		  }
	 }
}

代码3.68

object Demo {
    def main(args: Array[String]) {

        //创建迭代器
  	    val iter = Iterator("Hadoop","Spark","Scala")

		//循环输出迭代器指向对象中的所有元素
		for (elem <- iter) {
			println(elem)
		}
    }
}

代码3.69

scala> (1,2)  //不声明,直接创建元组
res0 :(Int, Int) = (1,2)

scala> 1->2   //同(1,2)  
res1:(Int, Int) = (1,2)

scala> (1,"Alice","Math",95.5)// 不声明,直接创建不同类型元素的元组
res2: (Int, String, String, Double) = (1,Alice,Math,95.5) 

代码3.70

object Demo {
    def main(args: Array[String]) {

         //创建元组
         val tuple = ("BigData",2019,45.0)

         //输出元组中元素
         println(tuple._1)
         println(tuple._2)
         println(tuple._3)
    }
}

代码3.71

scala> def sum(x:Int,y:Int)=return x+y
<console>:7: error: method sum has return statement;needs result type
def sum(x:Int,y:Int)=return x+y

代码3.72

scala> def gcd(x:Int,y:Int)= {
	if(x%y==0)  return y 
	else return gcd(x,x%y)
}
<console>:12:error:recursive method gcd needs result type
      gcd(x,x%y)

代码3.73

//定义列表numList
scala> val numList = List(-3, -5, 1, 6, 9)
numList: List[Int] = List(-3, -5, 1, 6, 9)

//不使用占位符作列表过滤操作
scala> numList.filter(x => x > 0 )
res1: List[Int] = List(1, 6, 9)

//使用占位符做列表过滤操作
scala> numList.filter(_ > 0)
res2: List[Int] = List(1, 6, 9)

代码3.74

scala> def combination(x:Int,y:Int,f:(Int,Int)=>Int)=f(x,y)
combination:(x:Int,y:Int,f:(Int,Int)=>Int)Int

scala> combination(23,12,_*_)
res3:Int = 276

代码3.75

scala> def tripleOp(a:Int,b:Int,c:Int,f:(Int,Int,Int)=>Int) =f(a,b,c)
tripleOp:(a:Int,b:Int,c:Int,f:(Int,Int,Int)=>Int) Int

scala> tripleOp(23,92,14,_*_+_)
res4: Int = 2130

代码3.76

scala> def tripleOp[A,B](a:A,b:A,c:A,f:(A,A,A)=>B)=f(a,b,c)
tripleOp:[A,B](a:A,b:A,c:A,f(A,A,A)=>B)B

scala> tripleOp[Int,Int](23,92,14,_*_+_)
res5: Int =2130

scala> tripleOp[Int,Double](23,92,14,1.0*_ /_ /_)
res6: Double =0.017857142857142856

scala> tripleOp[Int,Boolean](23,92,14,_>_+_)
res7: Boolean = false

代码3.77

object Demo {
     def main(args: Array[String]) {
        for (i <- 1 to 10)
           println( "Factorial of " + i + ": = " + factorial(i) )
      }
   
     def factorial(n: BigInt): BigInt = {  
        if (n <= 1)
           1  
        else    
           n * factorial(n - 1)
      }
}

代码3.78

object Demo {
    def main(args: Array[String]) {
	 	//求5的阶乘
	 	println(factorial(5,1)) 

	 	//尾递归求阶乘
	 	@annotation.tailrec //告诉编译器要尾递归
	 	def factorial(n:Int,m:Int):Int={
           if(n<=0) m
           else factorial(n-1,m*n) 
		}     
    }
}

代码3.79

object Demo {

     def main(args: Array[String]) {
        println( factorial(3) )
     }

     //计算阶乘
     def factorial(i: Int): Int = {
        def fact(i: Int, accumulator: Int): Int = {
           if (i <= 1)
              accumulator
           else
              fact(i - 1, i * accumulator)    
         }
    
	 //调用内部函数
        fact(i, 1) 
     }
}

代码3.80

object Demo {
     def main(args: Array[String]) {
        println( apply( layout, 10) )
      }

     def apply(f: Int => String, v: Int) = f(v)

     def layout[A](x: A) = "[" + x.toString() + "]"
}

代码3.81

//把匿名函数定义为一个值,赋值给myNumFunc变量
scala> val myNumFunc: Int=>Int = (num: Int) => num * 2    
myNumFunc: Int => Int = <function1>  

//调用myNumFunc函数,给出参数值3,得到乘法结果是6
scala> println(myNumFunc(3))     
6

代码3.82

scala> var i=15
i:Int=15

//定义一个函数字面量f,函数中使用了前面定义的变量i
scala> var f=(x:Int)=>x+i
f:Int=>Int=<function1>

//执行函数
scala> f(10)
res0:Int=25

//变量重新赋值
scala> i=20
i:Int=20

//执行函数
scala> f(10)
res1:Int=30

代码3.83

//Array类型的map函数使用
scala> Array("Hadoop", "Hive", "HDFS").map(_*2)//字符串加倍
res0: Array[String] = Array(HadoopHadoop, HiveHive, HDFSHDFS)

//List类型的map函数使用
scala> val list = List("Hadoop"->1, "Hive"->2, "HDFS"->2)
list: List[(String,Int)] = List((Hadoop,1), (Hive,2), (HDFS,2))

//省略值函数的输入参数类型
scala> list.map(x=>x._1)  
res1: List[String] = List(Hadoop, Hive, HDFS)

//参数x在=>中只出现一次,进一步简化
scala> list.map(_._1)  
res2: List[String] = List(Hadoop, Hive, HDFS)

//Map类型的map函数使用
scala> Map("Hadoop"->1, "Hive"->2, "HDFS"->3).map(_._1)
res3: scala.collection.immutable.Iterable[String] = List(Hadoop, Hive, HDFS)

scala> Map("Hadoop"->1, "Hive"->2, "HDFS"->2).map(_._2)
res4: scala.collection.immutable.Iterable[Int] = List(1,2,3)

代码3.84

scala> val books = List("Hadoop","Hive","HDFS")
books: List[String] = List(Hadoop, Hive, HDFS)

scala> books.flatMap (s => s.toList)
res0: List[Char] = List(H, a, d,o, o, p, H, i, v, e, H, D, F, S)

代码3.85

scala> val listInt=List(1,4,6,8,6,9,12)
listInt:List[Int]=List(1,4,6,8,6,9,12)

//返回所有偶数元素构成的集合
scala>listInt.filter(x=>x%2==0)
res0:List[Int]=List(4,6,8,12)

//简化的写法
scala> listInt.filter(_%2==0)
res1:List[Int]=List(4,6,8,12)

代码3.86

scala> val list = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> list.reduceLeft((x:Int,y:Int)=>{println(x,y);x+y})
(1,2)
(3,3)
(6,4)
(10,5)
res0: Int = 15

scala> list.reduceRight((x:Int,y:Int)=>{println(x,y);x+y})
(4,5)
(3,9)
(2,12)
(1,14)
res1: Int = 15

代码3.87

scala> val list = List(1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5)

scala> list.reduceLeft((x:Int,y:Int)=>{println(x,y);x-y})
(1,2)
(-1,3)
(-4,4)
(-8,5)
res2: Int = -13

scala> list.reduceRight((x:Int,y:Int)=>{println(x,y);x-y})
(4,5)
(3,-1)
(2,4)
(1,-2)
res3: Int = 3

代码3.88

scala> val list = List(1,2,4,3,5)
list: List[Int] = List(1, 2, 4, 3, 5)

scala> list.fold(10)(_*_)
res0: Int = 1200

代码3.89

scala> list.foldLeft(0)((x:Int,y:Int)=>{println(x,y);x+y})
(0,1)
(1,2)
(3,4)
(7,3)
(10,5)
res1: Int = 15

scala> list.foldRight(0)((x:Int,y:Int)=>{println(x,y);x+y})
(5,0)
(3,5)
(4,8)
(2,12)
(1,14)
res2: Int = 3