《快学scala》第七章课后习题:
1.编写示例程序,展示为什么
package com.horstmann.impatient
不同于
package com
package horstmann
package impatient
2.编写一段让你的Scala朋友们感到困惑的代码,使用一个不在顶部的com包这样可以吗?
3.编写一个包random,加入函数nextInt():Int,nextDouble():Double,setSeed(seed:Int):Unit。生成随机数的算法采用线性同余生成器:
后值 = (前值 * a + b)mod 2^n 其中,a = 1664525,b=1013904223,n = 32,前值的初始值为seed
4.在你看来Scala的设计者为什么要提供package object语法而不是简单的让你将函数和变量添加到包中呢?
5.private[com] def giveRaise(rate:Double)的含义是什么?有用吗?
6.编写一段程序,将Java哈希映射中的所有元素拷贝到Scala哈希映射。用引入语句重命名这两个类。
7.在前一个练习中,将所有引入语句移动到尽可能小的作用域里
8.以下代码的作用是什么?这是个好主意吗?
import java._
import javax._
9.编写一段程序,引入java.lang.System类,从user.name系统属性读取用户名,从Console对象读取一个密码,如果密码不是"secret",则在标准错误流中打印一个消息;如果密码是"secret",则在标准输出流中打印一个问候消息。不要使用任何其他引入,也不要使用任何限定词(带句点的那种)
10.除了StringBuilder,还有哪些java.lang的成员是被scala包覆盖的?
///
package SK
/**
* Created by sendoh on 2015/5/5.
*/
//7.1
package com {
class T1(){}
package horstmann{
class T2(t: T1){}
package impatient{
class T3(t1: T1, t2: T2){}
}
}
}
package com.horstmann.impatient{
//class T3(t1: T1, t3: T3){}
}
//2
package com {
class T1(){}
package horstmann{
class T2(t: T1){}
package impatient{
class T3(t1: T1, t2: T2){}
}
}
}
import com._
import scala.collection.mutable
class T5(t1: T1){
}
//3
package random1{
package object random1{
var seed: Int = _
val a = BigDecimal(1664525)
val b = BigDecimal(1013904223)
val n = 32
def nextInt(): Int = {
val temp = (seed * a + b) % BigDecimal(2).pow(n)
seed = temp.toInt
seed
}
def nextDouble(): Double = {
val temp = (seed * a + b) % BigDecimal(2).pow(n)
seed = temp.toInt
temp.toDouble
}
}
}
package Text{
import random1.random1
object Text extends App{
random1.seed = 4
println(random1.nextDouble())
println(random1.nextDouble())
println(random1.nextDouble())
println(random1.nextDouble())
println(random1.nextInt())
println(random1.nextInt())
println(random1.nextInt())
println(random1.nextInt())
}
}
//4
//、、、、、、、、、、
//5
//只有com包可以访问,其它包都不可以访问
//6
import java.util.{HashMap => JavaHashMap}
import scala.collection.mutable.HashMap
object Test1 extends App{
val map = new JavaHashMap[String, String]()
map.put("1", "a")
map.put("2", "b")
map.put("3", "c")
val map1 = new HashMap[String, String]()
for (key <- map.KeySet().toArray){
map1 += (key.toString -> map.get(key))
}
println(map1.mkString)
}
//7
object Test1 extends App{
import java.util.{HashMap => JavaHashMap}
val map = new JavaHashMap[String, String]()
map.put("1", "a")
map.put("2", "b")
map.put("3", "c")
import scala.collection.mutable.HashMap
val map1 = new HashMap[String, String]()
for (key <- map.KeySet().toArray){
map1 += (key.toString -> map.get(key))
}
println(map1.mkString)
}
//8
//导入java和javax下的所有类。而java和javax下是没有类的。所以此代码无用
//9
import java.lang.System
object Text2 extends App{
var password = Console.readLine()
if (password equals "secret")
System.out.println("Hello " + System.getProperty("user.name"))
else
System.err.println("Password error!")
}
//10
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
///
SparkPageRank:
package llf
import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.SparkContext._
/**
* Created by sendoh on 2015/5/5.
*/
object SparkPageRank { //网页排名,又称网页级别、Google左侧排名或佩奇排名,是一种根据网页之间相互的超链接计算的技术,而作为网页排名的要素之一
def showWarning(): Unit ={
System.err.println("""WARN: This is a naive implementation of PageRank and is given as an example!
|Please use the PageRank implementation found in org.apache.spark.graphx.lib.PageRank
|for more conventional use.
""".stripMargin)
}
//
def main(args: Array[String]): Unit ={
if (args.length < 1){
System.err.println("Usage: SparkPageRank <file> <iter>")
System.exit(1)
}
showWarning()
//
val conf = new SparkConf().setAppName("SparkPageRank")
val sc = new SparkContext(conf)
//
val iters = if (args.length > 0) args(1).toInt else 10
val lines = sc.textFile(args(0), 1)
val links = lines.map{ s =>
val parts = s.split("\\s+")
(parts(0), parts(1))
}.distinct().groupByKey().cache()
var ranks = links.mapValues(v => 1.0)
for (i <- 1 to iters){
val contribs = links.join(ranks).values.flatMap{ case (urls, rank) =>
val size = urls.size
urls.map(url => (url, rank / size))
}
ranks = contribs.reduceByKey(_ + _).mapValues(0.15 + 0.85 * _)
}
val output = ranks.collect()
output.foreach(tup => println(tup._1 + " has rank: " + tup._2 + "."))
sc.stop()
}
}
///
《快学scala》第八章课后习题:
1.扩展如下的BankAccount类,新类CheckingAccount对每次存款和取款都收取1美元的手续费
class BankAccount(initialBalance:Double){
private var balance = initialBalance
def deposit(amount:Double) = { balance += amount; balance}
def withdraw(amount:Double) = {balance -= amount; balance}
}
2.扩展前一个练习的BankAccount类,新类SavingsAccount每个月都有利息产生(earnMonthlyInterest方法被调用),并且有每月三次免手续费的存款或取款。在earnMonthlyInterest方法中重置交易计数
3.翻开你喜欢的Java或C++教科书,一定会找到用来讲解继承层级的实例,可能是员工,宠物,图形或类似的东西。用Scala来实现这个示例
4.定义一个抽象类Item,加入方法price和description。SimpleItem是一个在构造器中给出价格和描述的物件。利用val可以重写def这个事实。Bundle是一个可以包含其他物件的物件。其价格是打包中所有物件的价格之和。同时提供一个将物件添加到打包当中的机制,以及一个适合的description方法
5.设计一个Point类,其x和y坐标可以通过构造器提供。提供一个子类LabeledPoint,其构造器接受一个标签值和x,y坐标,比如:new LabeledPoint("Black Thursday",1929,230.07)
6.定义一个抽象类Shape,一个抽象方法centerPoint,以及该抽象类的子类Rectangle和Circle。为子类提供合适的构造器,并重写centerPoint方法
7.提供一个Square类,扩展自java.awt.Rectangle并且是三个构造器:一个以给定的端点和宽度构造正方形,一个以(0,0)为端点和给定的宽度构造正方形,一个以(0,0)为端点,0为宽度构造正方形
8.编译8.6节中的Person和SecretAgent类并使用javap分析类文件。总共有多少name的getter方法?它们分别取什么值?(提示:可以使用-c和-private选项)
9.在8.10节的Creature类中,将val range替换成一个def。如果你在Ant子类中也用def的话会有什么效果?如果在子类中使用val又会有什么效果?为什么?
10.文件scala/collection/immutable/Stack.scala包含如下定义:class Stack[A] protected (protected val elems: List[A]) 请解释protected关键字的含义
///
package llf
/**
* Created by sendoh on 2015/5/7.
*/
//8.1
class BankAccount(initialBalance: Double) {
private var balance = initialBalance
def deposit(amount: Double) = {balance += amount; balance}
def withdraw(amount: Double) = {balance -= amount; balance }
}
class CheckingAccount(initialBalance: Double) extends BankAccount(initialBalance){
override def deposit(amount: Double): Double = super.deposit(amount - 1)
override def withdraw(amount: Double): Double = super.withdraw(amount + 1)
}
//2
class SavingsAccount(initialBalance: Double) extends BankAccount(initialBalance){
private var num: Int = _
def earnMonthlyInterest() = {
num = 3
super.deposit(1)
}
override def deposit(amount: Double): Double = {
num -= 1
if (num < 0)
super.deposit(amount - 1)
else
super.deposit(amount)
}
override def withdraw(amount: Double): Double = {
num -= 1
if (num < 0)
super.withdraw(amount + 1)
else
super.withdraw(amount)
}
}
//3
class A{
def AA(){println("a")}
}
class B extends A{
override def AA(){println("b")}
}
class C extends B{
override def AA(){println("c")}
}
//4
import collection.mutable.ArrayBuffer
abstract class Item{
def price(): Double//方法
def description(): String
override def toString(): String = {
"description: " + description() + " price:" + price()
}
}
class SimpleItem(val price: Double, val description: String) extends Item{//构造器
//
}
class Bundle extends Item{
val items = new ArrayBuffer[Item]()
def addItem(item: Item): Unit ={
items += item
}
def price(): Double = {
var total = 0d
items.foreach(total += _.price())
total
}
def description(): String = {
items.mkString(" ")
}
}
//5
class Point(x: Int, y: Int){
//
}
class LabeledPoint(label: String, x: Int, y: Int) extends Point(x, y){
//
}
//6
abstract class Shape{
def centerPoint()
}
class Rectangle(startX: Int, startY: Int, endX: Int, endY: Int) extends Shape{
def centerPoint(){}
}
class Circle(x: Int, y: Int, radius: Double) extends Shape{
def centerPoint(){}
}
//7
import java.awt.{Point, Rectangle}
class Square(point: Point, width: Int) extends Rectangle(point.x, point.y, width, width){
def this(){
this(new Point(0, 0), 0)
}
def this(width: Int){
this(new Point(0, 0), width)
}
}
//8
// 2个。Person中取得的是传入的name,而SecretAgent中取得的是默认的"secret"
//9
//在Ant中使用def没有问题。但是如果使用val则无法编译。因为val只能重写不带参数的def。这里的def是带参数的
//10
//此构造方法只能被其子类来调用,而不能被外界直接调用