1. 程式人生 > >《快學scala》習題詳解 第1章 基礎

《快學scala》習題詳解 第1章 基礎

1 輸入3按Tab沒反應,加了.空格鍵才會觸發

會將Int轉為RichInt

2. 對3開方再乘方
scala> import math._
import math._

scala> math.sqrt(3)
res0: Double = 1.7320508075688772

scala> math.pow(res0,2)
res1: Double = 2.9999999999999996
3 通過賦值,產生錯誤,因此是var
scala> res0=3
<console>:15: error: reassignment to val
       res0=3
^
4 “crazy”*3,”crazy”將被複制3次
scala> "crazy"*3
res2: String = crazycrazycrazy

方法位於StringOps中

5. 10 max 2,找出最大值,處於BigInt
scala> 10 max 2
res0: Int = 10
6. 用BigInt計算2的1024次方

直接使用pow方法出錯

scala> val x:BigInt=math.pow(2,1024)
<console>:11: error: type mismatch;
 found   : Double
 required: BigInt
       val x:BigInt=math
.pow(2,1024)

使用BigInt的方法

scala> BigInt(2).pow(1024)
res1: scala.math.BigInt = 179769313486231590772930519078902473361797697894230657
27343008115773267580550096313270847732240753602112011387987139335765878976881441
66224928474306394741243777678934248654852763022196012460941194530829520850057688
38150682342462881473913110540827237163350510684586298239947245938479716304835356
329624224137216
7. 為了在使用probablePrime(100,Random)獲取隨機素數時不在probablePrime和Radom之前使用任何限定符,你需要引入什麼?

獲取長度為100位(二進位制)的隨機素數

probablePrime是BigInt中的方法,Random是Util中的

scala> import math.BigInt._
import math.BigInt._

scala> import util._
import util._

scala> probablePrime(100,Random)
res8: scala.math.BigInt = 1251608343750013616100676054601
8. 建立隨機檔案的方式之一是生成一個隨機的BigInt,然後將它轉換成三十六進位制,輸出類似”qsnvbevtomcj38o06kul”這樣的字串。

def toString(radix:Int),將BigInt轉換為指定的進位制數

scala> scala.math.BigInt(scala.util.Random.nextInt).toString(36)
res12: String = -7kqjpc
scala> scala.math.BigInt(scala.util.Random.nextInt).toString(2)
res19: String = 1011100101110001000111100111010
9. 獲取首尾字元

//獲取反向迭代器

scala> "Scala"(0)
res30: Char = S

scala> var x= "Scala".reverseIterator
x: Iterator[Char] = non-empty iterator

scala> x.next()
res25: Char = a
10. take,drop,takeRight和dropRight這些字串函式是做什麼用的?和substring相比,他們的優點和缺點都是哪些?
take/drop/takeRight/dropRight位於StringOps中

def take (n:Int):String // 獲取前n個元素
def takeRight(n: Int): String //獲取最後n個元素
def drop(n: Int): String //獲取所有元素,除了前n個
def dropRight(n: Int): String //獲取所有元素,除了最後n個

substring呼叫的是java的方法
def substring(arg0: Int): String // 擷取所有字元,除了前n個,類似drop(索引從1開始)
def substring(arg0: Int, arg1: Int): String //從索引[arg0,arg1)擷取字串(索引從0開始)

對於文章中出現在數字列表,論壇支援的實在不好,有時間了自己搭站點了