快学Scala课后习题答案

分享一个之前做快学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()
  }
}

转载于:https://www.cnblogs.com/miss24/p/5574656.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值