一、內(nèi)置控制結(jié)構(gòu)
遂溪ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書(shū)未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書(shū)銷(xiāo)售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書(shū)合作)期待與您的合作!1、if表達(dá)式
val filenameNice = if (!args.isEmpty) args(0) else "default.txt"
2、while循環(huán)
不管是while還是do...while,我們都不能叫做表達(dá)式,而應(yīng)該叫做循環(huán),因?yàn)樗鼈儾粫?huì)計(jì)算出一個(gè)新值。它們的值類(lèi)型是Unit,在scala中Unit和()是相等的
def gcdLoop(x: Long, y: Long): Long = {
var a = x
var b = y
while (a != 0) {
val temp = a
a = b % a
b = temp
}
b
}
do...while...表達(dá)式
var line = ""
do {
line = scala.io.StdIn.readLine()
println("Read: " + line)
} while (line != "")
在scala中給var重新賦值,永遠(yuǎn)都是返回()(即Unit)
() != ""將永遠(yuǎn)返回true
var tempLine = ""
while ((tempLine = scala.io.StdIn.readLine()) != "") // This doesn't work!
println("Read: " + tempLine)
因?yàn)閣hile循環(huán)不計(jì)算出值,所以while的代碼不那么的函數(shù)式,一般都會(huì)含有var變量,
scala選擇保留while是因?yàn)橛行﹫?chǎng)景使用while的代碼的可讀性還是很強(qiáng)的
采用遞歸來(lái)消除掉var
def gcd(x: Long, y: Long): Long =
if (y == 0) x else gcd(y, x % y)
3、for表達(dá)式
用for表達(dá)式迭代一個(gè)任意集合
val filesHere = (new java.io.File(".")).listFiles
for (file <- filesHere)
println(file)
for表達(dá)式中的過(guò)濾
for (
file <- filesHere
if file.isFile
if file.getName.endsWith(".scala")
) println(file)
嵌套迭代(nested iteration)
def grep(pattern: String) =
for (
file <- filesHere
if file.getName.endsWith(".scala");
line <- fileLines(file)
if line.trim.matches(pattern)
) println(file + ": " + line.trim)
可以在迭代的過(guò)程中,綁定中間值到一個(gè)變量
上面的()可以換成{},這樣每一個(gè)語(yǔ)句后面的分號(hào)就可以省略
def grepBindValue(pattern: String) =
for {
file <- filesHere
if file.getName.endsWith(".scala")
line <- fileLines(file)
trimmed = line.trim
if trimmed.matches(pattern)
} println(file + ": " + trimmed)
for ... yield ... 可以生成一個(gè)新的集合
//返回的是Array,是因?yàn)閒ilesHere的類(lèi)型是Array
def scalaFiles: Array[File] =
for {
file <- filesHere
if file.getName.endsWith(".scala")
} yield file
val forLineLengths: List[Int] =
for {
file <- filesHere.toList
if file.getName.endsWith(".scala")
line <- fileLines(file)
trimmed = line.trim
if trimmed.matches(".*object.*")
} yield trimmed.length
4、異常處理
scala中拋異常使用throw關(guān)鍵字,異常的捕獲用catch關(guān)鍵字。捕獲到異常后,可以計(jì)算并返回一個(gè)值
val n = 5
val half: Int =
if (n % 2 == 0)
n / 2
else
throw new RuntimeException("n must be even")
println(half)
try {
//val f = new FileReader("input.txt") //這個(gè)會(huì)拋FileNotFoundException
// Use and close file
throw new IOException("test")
} catch {
case e @(_: FileNotFoundException | _: IOException) => {
// Handle missing file
println("All Exception = " + e.getMessage)
}
case ex: Exception => {
// Handle other I/O error
println("IOException = " + ex.getMessage)
}
}
val file = new FileReader("input.txt")
try {
// Use the file
} finally {
file.close() // Be sure to close the file
}
5、break和continue
非得使用break的話,我們可以使用scala.util.control中的break
import scala.util.control.Breaks._
import java.io._
val in = new BufferedReader(new InputStreamReader(System.in))
breakable {
while (true) {
println("? ")
if (in.readLine() == "") break
}
}
二、函數(shù)
1、本地函數(shù)。定義在函數(shù)內(nèi)部的函數(shù)為本地函數(shù),智能被此函數(shù)內(nèi)部調(diào)用。
def processFile(filename: String, width: Int) = {
//本地函數(shù)
def processLine(line: String) = {
if (line.length > width)
println(filename + ": " + line.trim)
}
val source = Source.fromFile(filename)
for (line <- source.getLines())
processLine(line)
}
2、first class function 函數(shù)可以作為函數(shù)的參數(shù)進(jìn)行傳遞
3、函數(shù)的參數(shù)
不定長(zhǎng)參數(shù)
def echo(args: String*) =
for (arg <- args) println(arg)
使用參數(shù)名字來(lái)給參數(shù)設(shè)置值
def speed(distance: Float, time: Float): Float =
distance / time
speed(distance = 100, time = 10)
默認(rèn)參數(shù)值
def printTime(out: java.io.PrintStream = Console.out) =
out.println("time = " + System.currentTimeMillis())
printTime()
printTime(Console.err)
4、函數(shù)閉包
函數(shù)捕獲一個(gè)自由變量而變成一個(gè)閉包。 每次調(diào)用函數(shù)的時(shí)候都產(chǎn)生一個(gè)新的閉包。
var more = 1
val addMore = (x: Int) => x + more //函數(shù)捕獲一個(gè)自由變量而變成一個(gè)閉包
addMore(10)
當(dāng)自由變量的值改變的時(shí)候,閉包對(duì)自由變量的改變也是可以捕獲的到
more = 9999
addMore(10)
val someNumbers = List(-11, -10, -5, 0, 5, 10)
var sum = 0
someNumbers.foreach(sum += _)
println(sum)
5、尾遞歸
什么是尾遞歸呢?如果調(diào)用自身方法的動(dòng)作是函數(shù)體的最后一個(gè)動(dòng)作的話,那么這個(gè)遞歸就是一個(gè)尾遞歸
遞歸:更函數(shù)式、簡(jiǎn)潔以及沒(méi)有var,但是函數(shù)的調(diào)用可能會(huì)消耗點(diǎn)時(shí)間。while循環(huán)是命令式編程,可能會(huì)更高效的,因?yàn)闆](méi)有方法的調(diào)用。但是如果是尾遞歸的話,編譯器是會(huì)優(yōu)化的,其效率和while循環(huán)是一樣的
可以使用注解tailrec來(lái)標(biāo)志是否為尾遞歸
@tailrec
def boom(x: Int): Int =
if (x == 0) throw new Exception("boom!")
else boom(x - 1)
尾遞歸的限制,以下遞歸,不會(huì)進(jìn)行尾遞歸優(yōu)化,因?yàn)閖vm的指令集使得尾遞歸的優(yōu)化受限
遞歸調(diào)用的函數(shù)不是函數(shù)體所在的函數(shù)
def isEven(x: Int): Boolean =
if (x == 0) true else isOdd(x - 1)
def isOdd(x: Int): Boolean =
if (x == 0) false else isEven(x - 1)
三、高階函數(shù)及函數(shù)柯里化
高階函數(shù)(high-order functions)就是用函數(shù)作為參數(shù)的函數(shù)。高階函數(shù)可以減少冗余代碼,高階函數(shù)可以使得客戶(hù)端代碼簡(jiǎn)潔。
def filesEnding(query: String) =
for (file <- filesHere; if file.getName.endsWith(query))
yield file
def filesContaining(query: String) =
for (file <- filesHere; if file.getName.contains(query))
yield file
改造后:
private def filesMatching(matcher: String => Boolean) =
for (file <- filesHere; if matcher(file.getName))
yield file
柯里化
//柯里化函數(shù)(curring function)
def curriedSum(x: Int)(y: Int) = x + y
curriedSum(1)(2)
//說(shuō)明柯里化的過(guò)程
def first(x: Int) = (y: Int) => x + y
val second = first(1)
second(2)
示例:自定義循環(huán)控制語(yǔ)句
var i = 10
while (i == 0) {
i -= 1
println(i)
}
until(i == 0) {
i -= 1
println(i)
}
def until(condition: => Boolean)(block: => Unit) {
if (!condition) {
block
until(condition)(block)
}
}
by name by value
by name 執(zhí)行的時(shí)候才執(zhí)行,by value調(diào)用就執(zhí)行
//by-name parameter
def byNameAssert(predicate: => Boolean) =
if (assertionsEnabled && !predicate)
throw new AssertionError
byNameAssert(5 > 3)
//by-value parameter
def boolAssert(predicate: Boolean) =
if (assertionsEnabled && !predicate)
throw new AssertionError
boolAssert(5 > 3)
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。
網(wǎng)站欄目:4、Scala函數(shù)式基礎(chǔ)-創(chuàng)新互聯(lián)
瀏覽地址:http://aaarwkj.com/article38/ccpcpp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、網(wǎng)站改版、網(wǎng)站維護(hù)、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容