scala学习五:scala函数式编程
标签(空格分隔): scala
一,值函数
值函数:将函数作为变量的值
def myfun1(name:String):String="hello "+name
val v1=myfun1("tom")
println(myfun1(v1))
二,匿名函数
(x:Int) =>3*x
Array(1,2,3).map((x:Int)=>3*x)
//res1: Int => Int = <function1>
//res2: Array[Int] = Array(3, 6, 9)
三,带函数参数的函数
在scala中,可以将一个函数作为另一个函数的参数–高阶函数
def someAction(f:(Double) =>Double) = f(10)
import scala.math._
someAction(sqrt)
//someAction: someAction[](val f: Double => Double) => Double
//import scala.math._
//res3: Double = 3.1622776601683795
def mytest(x:Int,y:Int) ={x+y+100}
def myfunc(f:(Int,Int) =>Int,x:Int,y:Int)=f(x,y)
myfunc(mytest,1,2)
//mytest: mytest[](val x: Int,val y: Int) => Int
//myfunc: myfunc[](val f: (Int, Int) => Int,val x: Int,val y: Int) => Int
//res4: Int = 103
四,闭包
函数的嵌套,即:在一个函数定义中,包含另外一个函数的定义
def mul(factor:Double) =(x:Double) =>x*factor
val half=mul(0.5) //0.5传给factor
println(half(10)) //10传给x
五,柯里化函数
把具有多个参数的函数转换为一条函数链,每个节点上市单一的参数
//一个普通函数
def fun(x:Int,y:Int)=x*y
//柯里化函数
def fun1(x:Int)=(y:Int) => y*x
//简写形式
def fun2(x:Int)(y:Int) =x*y
fun(6,7)
fun1(6)(7)
六,高阶函数实例
1,map
在列表的每个元素上计算一个函数,并且返回一个包含相同数目元素的列表
val numbers=List(1,2,3,4,5,6,7,8)
numbers.map((i:Int) => i*2)
//res0: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16)
2,foreach
它和map比较相似,只不过它没有返回值
val numbers=List(1,2,3,4,5,6,7,8)
numbers.foreach((i:Int) => i*2)
3,filter
移除任何使得传入的函数返回false的元素
numbers.filter((i:Int) => i%3==0)
//res1: List[Int] = List(3, 6)
4,zip
把两个列表的元素合并成一个由元素对组成的列表里
List(1,2).zip(List(3,5)) //res2: List[(Int, Int)] = List((1,3), (2,5))
List(1,2,4).zip(List(3,5)) //res2: List[(Int, Int)] = List((1,3), (2,5))
5,partition
根据断言函数的返回值对列表进行拆分
numbers.partition((i:Int) => i%2==0)
// res4: (List[Int], List[Int]) = (List(2, 4, 6, 8),List(1, 3, 5, 7))
6,find
返回集合里面第一个符合条件的元素
numbers.find((i:Int) => i%2==0)
//res5: Option[Int] = Some(2)
7,flatten
可以吧嵌套的结构展开
List(List(1,2,3),List(4,5,6)).flatten
//res6: List[Int] = List(1, 2, 3, 4, 5, 6)
8,flatMap
faltMap是一个常用的combinator,它结合了map和flatten的功能
val mylist=List(List(1,2,3),List(4,5,6))
mylist.flatMap(x =>x.map(_*2))
//res7: List[Int] = List(2, 4, 6, 8, 10, 12)