大數據筆記(二十五)——Scala函數式編程
阿新 • • 發佈:2018-03-31
=== 情況 不能 nbsp 結構 map som class 編程
===================== Scala函數式編程 ========================
一、Scala中的函數
(*) 函數是Scala中的頭等公民,就和數字一樣,可以在變量中存放函數,即:將函數作為變量的值(值函數)。
def myFunc1(name:String):String = "Hello " + name println(myFunc1("Tom")) def myFunc2():String = "Hello World" //值函數:把函數作為變量的值 val v1 = myFunc1("Tom") val v2 = myFunc2() //再將v1付給myFunc1println(myFunc1(v1))
運行:
myFunc1: myFunc1[](val name: String) => String Hello Tom res0: Unit = () myFunc2: myFunc2[]() => String v1: String = Hello Tom v2: String = Hello World Hello Hello Tom res1: Unit = ()
二、匿名函數:沒有名字的函數
//匿名函數:沒有名字的函數 // 完整: def myFunc3(x:Int) = x * 3 (x:Int) => x*3 //舉例:Array(1,2,3) ====> (3,6,9) Array(1,2,3).map((x:Int) => x*3)
運行:
res2: Int => Int = <function1>
res3: Array[Int] = Array(3, 6, 9)
三、高階函數:帶函數參數的函數
註意:把一個函數作為另外一個函數的參數值
四、高階函數示例
//高階函數 import scala.math._ //對數字10進行某種運算 //f : 就是執行的運算 def someAction(f:(Double)=>Double) = f(10)//測試 //情況1:開平方 someAction(sqrt) someAction(sin) //另一個例子 def mytest(x:Int,y:Int):Int = { x*y + 10} //定義一個高階函數 def myFunction(f:(Int,Int)=>Int,x:Int,y:Int)=f(x,y) //調用 myFunction(mytest,2,3)
運行:
import scala.math._ someAction: someAction[](val f: Double => Double) => Double res0: Double = 3.1622776601683795 res1: Double = -0.5440211108893698 mytest: mytest[](val x: Int,val y: Int) => Int myFunction: myFunction[](val f: (Int, Int) => Int,val x: Int,val y: Int) => Int res2: Int = 16
數據:
val numbers = List(1,2,3,4,5,6,7,8,9,10)
map: 作用於列表中的每個元素,並且返回一個新的列表
numbers.map((i:Int) => i*2)
foreach: 跟map一樣,沒有返回值
numbers.foreach((i:Int) => i*2)
filter: 移除函數函數false的元素
返回所有能夠被2整除的元素
numbers.filter((i:Int)=> i%2 ==0 )
zip: 把兩個列表合並到一個列表中
List(1,2,3).zip(List(4,5,6))
數據:
val numbers = List(1,2,3,4,5,6,7,8,9,10)
partition: 能被2整除的放到一個分區中,不能被整除的放到另一個分區中
numbers.partition((i:Int) => i%2 ==0)
find: 第一個匹配條件的元素
找到第一個能被3整除的元素
numbers.find((x:Int) => x%3 == 0)
numbers.find(_ % 3 == 0)
flatten: 把一個嵌套的結構展開
List(List(1,2,3),List(4,5,6)).flatten
flatMap: 壓平,結合了map和flatten的功能
var myList = List(List(1,2,3),List(4,5,6))
myList.flatMap(x=>x.map(_ *2))
分為兩步
1、List(1,2,3),List(4,5,6) ===> 合並成一個List
2、再乘以2
運行以上例子的結果:
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) res0: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20) res1: Unit = () res2: List[Int] = List(2, 4, 6, 8, 10) res3: List[(Int, Int)] = List((1,4), (2,5), (3,6)) res4: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10),List(1, 3, 5, 7, 9)) res5: Option[Int] = Some(3) res6: Option[Int] = Some(3) res7: List[Int] = List(1, 2, 3, 4, 5, 6) myList: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6)) res8: List[Int] = List(2, 4, 6, 8, 10, 12) score: scala.collection.mutable.Map[String,Int] = Map(Mike -> 90) res9: Unit = () Map(Mike -> 85) res10: Unit = ()
五、閉包
六、柯裏化:Currying
大數據筆記(二十五)——Scala函數式編程