Coursera Scala 5-4:List的高阶函数
2014-07-11 16:49
183 查看
Coursera Scala 5-4:List的高阶函数
Recurring Patterns for Computations on Lists
重复出现的Lists计算模式lists的很多函数有相似的结构,重复出现的模式有:
用某个方法转换每个元素
用某个条件提取元素
用某种方法链接元素
函数式编程语言,让程序员能写出更通用的计算模式,通过使用高阶函数。
Applying a Function to Elements of a List
将一个list的所有元素,进行转换。例子:返回一个新的集合,每个元素乘以factordef scaleList(xs: List[Double],factor:Double):List[Double] = xs match { case Nil => xs case y::ys => y*factor :: scaleList(ys,factor) }
高阶函数:Map
上面的模式,可以通过map函数来进行通用性封装:abstract class List[T] {... def map[U](f: T=>U): List[U] = this match { case Nil => this case x::xs => f(x) :: xs.map(f) }
(实际上,map的定义更复杂,不仅仅只支持lists)
使用map,scaleList很容易被实现:
def scaleList(xs:List[Double],factor: Double) = xs map (x => x * factor)
高阶函数:Filtering
这是另外一个常用的操作。从集合中筛选满足条件的元素abstract class List[T] { ... def filter(p: T => Boolean): List[T] = this match { case Nil => this case x::xs => if(p(x)) x::xs.filter(p) else xs.filter(p) } }
filter还有其他变种:
xs fileterNot p 相当于xs fileter(x=>!p(x))
xs partition p 分区:List(1,0,1,0) partition (>0) // ((1,1),(0,0))
xs takeWhile p 用法:1 to 10 takeWhile (<5) // (1,2,3,4)
xs dropWhile p 用法:1 to 10 dropWhile (<5) // (5,6,7,8,9,10)
xs span p 用法:1 to 10 span (<5) // ((1,2,3,4),(5,6,7,8)
Excercise
编写函数pack满足:List("a","a","a","b","b","c","c","a")
=>
List( List("a","a","a"), List("b","b"), List("c","c"),List("a") )
def pack[T](xs: List[T]): List[List[T]] = xs match { case Nil => Nil case x :: xs1 => val (first,rest) = xs span (y=>y==x) first :: pack(rest) }
Excercise2
编写函数encode满足:List("a","a","a","b","b","c","c","a")
=>
List( List("a",3), List("b",2), List("c",2),List("a",1) )
def encode[T](xs: List[T]): List[(T,Int)] = pack(xs) map (ys => (ys.head, ys.length))
[/code]
相关文章推荐
- Coursera Scala 5-5 List:Reduction of Lists
- scala高阶函数实现类似sql查询
- scala版本更新之后List.make()函数的更改
- 【Coursera】Algorithms, Part I 算法C++实现:Stacks Linked-list
- scala - working with List
- 今天想当然地被scala小坑了一下,Source的getLines回返的是Iterator我想当然地以为是list.
- Coursera Scala 5-2:Pairs和Tuple
- scala LinkedList 瑕疵
- Coursera为什么喜欢Scala
- scala入门-09 scala高阶函数
- scala集合List和Set
- scala List和Tuple的用法
- scala 关于Array,List,Tuple的区别
- 【Scala】高阶函数和柯里化
- scala list
- Scala 深入浅出实战经典 第39讲:ListBuffer、ArrayBuffer、Queue、Stack操作代码实战
- Scala的map高阶函数应用
- scala 两个list 拼接 ++:
- scala学习笔记--高阶函数
- 第81讲:Scala中List的构造是的类型约束逆变、协变、下界