分享一個之前做快學Scala的課后習題(2-21章節,19無)的Github鏈接,我把習題的文字寫在了每個回答的注釋上面,這樣方便大家對照着看,省的回過頭去對照着pdf看了,如果有做的不對的地方希望大家給予指正。
github鏈接如下,http://github.com/fxxkinglife/scala-hello。
舉一個第二章節的例子,拋磚引玉:
object charpter02 {
/*
* 2.1
* 一個數字如果為正數,則它的signum為1;
* 如果是負數,則signum為-1;
* 如果為0,則signum為0.編寫一個函數來計算這個值
* */
def signum(x: Int): Int = {
if (x > 0) { 1 }
else if (x < 0) { -1 }
else { 0 }
}
def signum(x: Int): Int = if (x > 0) 1 else if (x < 0) -1 else 0;
def signum(x: Int) = { if (x > 0) 1 else if (x < 0) -1 else 0 }
def signum(x: Int) = if (x > 0) 1 else if (x < 0) -1 else 0
/*
* 2.2
* 一個空的塊表達式{}的值是什么?類型是什么?
* */
// def checkEmptyBlockType() = {
// println({});
// println({}.getClass())
// }
def checkEmptyBlockType { println({}); println({}.getClass()) }
/*
* 2.3
* 指出在Scala中何種情況下賦值語句x=y=1是合法的。
* (提示:給x找個合適的類型定義)
*/
def checkAssignLegal {
var x: Unit = ()
println("x's type is: " + x.getClass)
var y = 1
x = y = 1
}
/*
* 2.4
* 針對下列Java循環編寫一個Scala版本:
* for(int i=10;i>=0;i–) System.out.println(i);
*/
def ScalaForeach {
// 1.to(10).reverse.foreach { (i: Int) => Predef.println(i) }
// 1.to(10).reverse.foreach { i => Predef println i }
// 1.to(10).reverse.foreach { i => println(i) }
// 1.to(10).reverse foreach { println _ }
(1 to 10 reverse) foreach println
}
/*
* 2.5
* 編寫一個過程countdown(n:Int),打印從n到0的數字
*/
def countdown(n: Int) {
n match {
case n if n >= 0 => {
(0 to n reverse) foreach println
}
case n if n < 0 => {
n to 0 foreach println
}
}
}
/*
* 2.6
* 編寫一個for循環,計算字符串中所有字母的Unicode代碼的乘積。
* 舉例來說,"Hello"中所有字符串的乘積為9415087488L
*/
def calculateCharsUnicodeProduct(s: String) = {
var res: Long = 1
s foreach { res *= _.toLong }
res
}
/*
* 2.7
* 同樣是解決前一個練習的問題,但這次不使用循環。
* (提示:在Scaladoc中查看StringOps)
*/
// def computeCharsUnicodeProduct(s: String) = (1.toLong /: s) { _ * _ }
def computeCharsUnicodeProduct(s: String) = s.foldLeft(1.toLong) { _ * _ }
/*
* 2.8
* 編寫一個函數product(s:String),
* 計算前面練習中提到的乘積
* 2.9
* 把前一個練習中的函數改成遞歸函數
*/
// def product(s: String) = {
// if (s.length() == 1) s(0) toLong
// else s(0).toLong * product(s.tail)
// }
def product(s: String): Long = {
if (s.length() == 1) s(0) toLong
else s(0).toLong * product(s.tail)
}
/*
* 2.10
* 編寫函數計算xn,其中n是整數,使用如下的遞歸定義:
*/
def question10(x: Int, n: Int): BigInt = n match {
case 0 => 1
case n if n < 0 => 1 / question10(x, -n)
case n if n % 2 == 0 => question10(x, n / 2) pow 2
case n if n % 2 == 1 => x * question10(x, n - 1)
}
def main(args: Array[String]): Unit = {
// checkEmptyBlockType()
}
}