## 2016年5月15日 星期日

### [Scala 小學堂] Scala Gossic : 了解更多 - 定義函式 (函式重載、區域函式、重複參數)

Scala 是一個可直譯、編譯、靜態、運行於 JVM 之上、可與 Java 互操作、融合物件導向編程特性與函式編程風格的程式語言. Scala 本身具有擴充性，不過這必須了解更多語法特性與細節.

- MoreFuncdef1.scala 代碼 :
1. def sum(a: Int, b: Int) = a+b
2. def sum(a: Int, b: Int, c: Int) = a + b + c
3.
4. println(sum(12)) // Show 3
5. println(sum(123))  // Show 6

- MoreFuncdef2.scala 代碼 :
1. def sum(a: Int, b: Int) = a+b
2. def sum(a: Long, b: Long) = a+b
3. println(sum(12))   // Using Int Version
4. println(sum(1L, 2L)) // Using Long version
5. println(sum(1, 2L))  // Using Long version

def sum(a: Long, b: Long) = a + b
println(sum(1, 2)) // 這是 OK 的

def sum(a: Int, b: Int) = a + b
println(sum(1L, 2L)) // type mismatch 錯誤

- MoreFuncdef3.scala 代碼 :
1. def selection(number: Array[Int]) {
2.         //Find minimum
3.         def min(m: Int, j:Int): Int={
4.                 if(j == number.length) m
5.                 else if(number(j) < number(m)) min(j, j+1)
6.                 else min(m, j+1)
7.         }
8.
9.         for(i <- nbsp="" span="">0 until number.length -1) {
10.                 val m = min(i, i+1);
11.                 if(m!=i) {
12.                         swap(number, i, m)
13.                         println("swap "+i+" with "+m)
14.                         number.foreach((x: Int) => print(x+" "))
15.                         println("\n")
16.                 }
17.         }
18. }
19.
20. def swap(number: Array[Int], i: Int, j: Int) {
21.         val t = number(i)
22.         number(i) = number(j)
23.         number(j) = t
24. }
25.
26. var arr = Array(101123817142933)
27. arr.foreach(println)
28. selection(arr)
29. arr.foreach(println)

- MoreFuncdef4.scala 代碼 :
1. def sum(numbers: Int*) = numbers.reduceLeft((sum, k) => sum + k)
2.
3. println(sum(12))
4. println(sum(123))
5. println(sum(1234))

scala> def sum(numbers: Int*) = numbers.reduceLeft((sum, k) => sum + k)
sum: (numbers: Int*)Int

scala> val numbers = Array(1,2)
numbers: Array[Int] = Array(1, 2)

scala> println(sum(1,2,3))
6

scala> println(numbers) // 錯誤 type mismatch

scala> println(sum(numbers:_*))
3

scala> def sum(numbers: Int*) = numbers.reduceLeft(_ + _)
sum: (numbers: Int*)Int

scala> println(sum(1, 2))
3

reduceLeft 方法第一次迭代時預設傳入函式物件的第一個參數值為 0，如果使用 foldLeft 的話，可以指定第一次的傳入值，例如 :
scala> def sum(numbers:Int*) = numbers.foldLeft(0){_+_}
sum: (numbers: Int*)Int

scala> println(sum(4,5))
9

scala> def sum(numbers:Int*) = (0/:numbers){_ + _}
sum: (numbers: Int*)Int

scala> println(sum(6,7))
13

[Scala 小學堂] Scala Gossic : 起步走 - 內建控制結構 (for 運算式)

### [ Python 文章收集 ] List Comprehensions and Generator Expressions

Source From  Here   Preface   Do you know the difference between the following syntax?  view plain copy to clipboard print ? [x  for ...