1. One thing you will notice is that almost all of Scala’s control structures result in some value

Scala的每种控制语句都是有值的

This is the approach taken by functional languages, in

which programs are viewed as computing a value, thus the components of a

program should also compute values

这是因为函数式语言认为程序的作用就是计算一个值,因此它的各个组件也应该计算一个值

2. while循环

	def gcdLoop(a: Int, b: Int): Int = {
	  var x = a; var y = b
	  var tmp = 0
	  while (y != 0) {
	  	tmp = y
	  	y = x % y
	  	x = tmp
	  }
	  x
	}

3. do..while循环

    var line = ""
    do {
      line = readLine()
      println("Read:"+ line)
    } while (line != "")
  }

4. Unit

The while and do-while constructs are called “loops,” not expressions,

because they don’t result in an interesting value. The type of the result is

Unit. It turns out that a value (and in fact, only one value) exists whose type

is Unit. It is called the unit value and is written (). The existence of () is

how Scala’s Unit differs from Java’s void

while和do while之所以叫做循环而不叫做表达式因为它们不产生任何有意义的值,这个无意义的值在Scala中叫做Unit,写做(), ()的存在是Scala的Unit不同于Java的void的地方

object TestSheet {
	
  def greet() { println("Hello!")}                //> greet: ()Unit
  greet == ()                                     //> Hello!
                                                  //| res0: Boolean = true
	  
}

5. 对var 赋值的语句也会产生Unit

object TestSheet {
	var a = 123                               //> a  : Int = 123
	(a = 456) == ()                           //> res0: Boolean = true
}

6. 为什么Scala中要包含while循环

Because the while loop results in no value, it is often left out of pure

functional languages. Such languages have expressions, not loops. Scala

includes the while loop nonetheless, because sometimes an imperative solution can be more readable, especially to programmers with a predominantly

imperative background. For example, if you want to code an algorithm that

repeats a process until some condition changes, a while loop can express it

directly while the functional alternative, which likely uses recursion, may be

less obvious to some readers of the code

因为不产生任何值,纯粹的函数式语言通常不包含while循环,然而scala包含了while循环。这是因为有时命令式语言的解决方案会更加可读,特别是对于有命令式语言编程背景的人

In general, we recommend you challenge while loops in your code in the

same way you challenge vars. In fact, while loops and vars often go hand

in hand. Because while loops don’t result in a value, to make any kind of

difference to your program, a while loop will usually either need to update

vars or perform I/O.

尽力不要使用while 循环和var, 除非迫不得已

while循环通常和var同时出现,因为while循环若想制造些不同,要么改变var的值,要么执行I/O操作


7.For表达式

Scala’s for expression is a Swiss army knife of iteration. It lets you combine

a few simple ingredients in different ways to express a wide variety of iterations. Simple uses enable common tasks such as iterating through a sequence

of integers. More advanced expressions can iterate over multiple collections

of different kinds, can filter out elements based on arbitrary conditions, and

can produce new collections.

Scala的for表达式可谓迭代的瑞士***。可以用不同的方式组合简单的成分表达多样的迭代。

最简单的应用是对一个整数序列做迭代

高级一点的应用包括对多个不同类型的集合做迭代

可以做筛选,也可以用于产生新的集合


8. 列出一个目录的所有文件 (Listing files in a directory with a for expression)

object TestMain {
  def main(args: Array[String]) {
	  	val files =  (new java.io.File("E:/")).listFiles()
	  	for (file <- files) println(file)
  }
}

9. Range对象上的跌代

 for (i <- 1 to 10) println("Iteration: " + i)

等同于

for (i <- 1 until 11) println("Iteration: " + i)

10.过滤以.txt结尾的文件

	val files = (new java.io.File("E:/")).listFiles()
	for (file <- files if file.getName().endsWith(".txt"))
	  println(file)

11.多个过滤条件

	val files = (new java.io.File("E:/")).listFiles()
	for (file <- files 
	    if file.getName().endsWith(".txt")
	    if file.getName().startsWith("data")
    ) println(file)

12. 多重迭代 (nested iteration)

	  for {
	    shape <- List("红桃","梅花","方块","黑桃")
	    num <- 1 to 12
	   } println(shape+num)

这里必须用花括号

13.上面的for语句同样可以加入if条件

	  for {
	    shape <- List("红桃","梅花","方块","黑桃")
	    num <- 1 to 12
	    if num % 3 == 0
	   } println(shape+num)

14. 迭代产生新的集合

语法: for clauses yield body

	  val oddNums = for (i <- 1 to 10 if i % 2 == 0) yield i
	  println(oddNums) //Vector(2, 4, 6, 8, 10)

15. try...finally...的返回值

 def f:Int = try { 1 } finally {2}                //> f: => Int
 f                                                //> res0: Int = 1

不是2而是1,一定出乎你的意料


16. match语句

	  val line = readLine()
	  line match {
	    case "yes" => println("your input is yes")
	    case "no" => println("got no")
	    case _ => println("not what I expected")
	  }

match语句中会返回值

match语句可以用于非常复杂的模式匹配,这里只是演示了最简单的用法


17.打印乘法表

package chapter7
object TestMain {
  def main(args: Array[String]) {
	// make sequence
    def makeSeq(n: Int) = for (i <- 1 to 9)  yield {
      val prod = (n * i).toString
      val pading = " " * (4 - prod.length)
      pading + prod
    }
    // make row
    def makeRow(n: Int) = makeSeq(n).mkString
    // make table
    def makeTable = {
      val tableSeq = for (r <- 1 to 9)  yield {
        makeRow(r)
      }
      tableSeq.mkString("\n")
    }
    
    println(makeTable)
  
  }
}

/* out put

   1   2   3   4   5   6   7   8   9
   2   4   6   8  10  12  14  16  18
   3   6   9  12  15  18  21  24  27
   4   8  12  16  20  24  28  32  36
   5  10  15  20  25  30  35  40  45
   6  12  18  24  30  36  42  48  54
   7  14  21  28  35  42  49  56  63
   8  16  24  32  40  48  56  64  72
   9  18  27  36  45  54  63  72  81


*/