代码都是写在scala worksheet里
2.1 一个数字如果为正数,则它的signum为1;如果是负数,则signum为-1;如果为0,则signum为0.编写一个函数来计算这个值
def signum (x: Int): Int = // signum: signum[](val x: Int) => Int
if (x > 0) 1
else if (x < 0) -1
else 0
signum(1) //res0: Int = 1
2.2 一个空的快表达式{}的值是什么?类型是什么?
{} = Unit
2.3 指出在Scala中何种情况下赋值语句x=y=1是合法的。(提示:给x找个合适的类型定义)
var y = 0
val x: Unit = y = 1
2.4 针对下列Java循环编写一个Scala版本:for(int i=10;i>=0;i–)System.out.println(i);
for (i <- 10 to 0 by -1)
println(i)
2.5 编写一个过程countdown(n:Int),打印从n到0的数字
def countdown (n: Int): Unit = {
for (i <- n to 0 by -1)
println(i)
}
countdown(10)
2.6 编写一个for循环,计算字符串中所有字母的Unicode代码的乘积。举例来说,”Hello”中所有字符串的乘积为9415087488L
var t: Long = 1
val s = "Hello"
for (ch <- s)
t *= ch.toLong
t
2.7 同样是解决前一个练习的问题,但这次不使用循环。(提示:在Scaladoc中查看StringOps)
var tt: Long = 1
s.foreach(tt *= _.toLong)
tt
2.8 编写一个函数product(s:String),计算前面练习中提到的乘积
同上
2.9 把前一个练习中的函数改成递归函数
def product(s: String): Long = {
if (s.length() == 0) 1
else s.head.toLong * product(s.tail)
}
product(s)
2.10 编写函数计算xn,其中n是整数,使用如下的递归定义:
- xn=y2 x n = y 2 ,如果 n n 是正偶数的话,这里的
- xn=x∗xn−1 x n = x ∗ x n − 1 ,如果 n n 是正奇数的话
xn=1/x−n x n = 1 / x − n ,如果 n n <script type="math/tex" id="MathJax-Element-8">n</script>是负数的话
def fastpow(x: Double, n: Int): Double = { if (n == 0) 1 else if (n < 0) 1 / fastpow(x, -n) else if (n % 2 == 1) fastpow(x, n - 1) * x else fastpow(x, n / 2) * fastpow(x, n / 2) } fastpow(2, 10)