pattern matching 生成list 或是vector等的技巧:
case class: a class that can use cases pattern
e match { case p1 => exp1 case p2 => exp2...}a match exception will be thrown if no match were found
p1 .. pn these patterns:use constructor to make sure the class, like Num(n) then you can use n, or Num(_), _ means everything. or Num(1)
--
for () yield will generate a collection, like Vector
someList.map(someMethod) will do the same
if the method generate some collections, like List, then map will generate List(List). To fully use List, use flatMap. e.g.:
val names = List(“Peter”, “Paul")
def foo(s:String) = Vectot(s.toUpperCase(), s.toLowerCase())
names.map(foo) generate List(Vector(“PETER”, “peter”), Vector(“PAUL”, “paul"))
name.flatMap(foo) generate List(“PETER”, “peter”, “PAUL”, “paul")
其他集合类型的基本用法:
List in Scala:
val test = List(1,2,3)val test2 = List(List(0,1,2), List(1,2,3), List(2,3,4))
Vector in Scala
val test = Vector(1,2,3)
near to random access, support all vector operations except :: is replaced by+: or :+ where : will point to sequences like x +: xs
Pair in Scala:val pair = (“answer”, 42) //get pair contentval (a, b) = pair//a = “string” b = 42
can be expanded to n-tuple
Map in Scala: iterating pairs in map: for ((k, v) <-map)processk and v iterating keys: scores.keySet //A set such asSet("Bob", "Cindy", "Fred", "Alice") iterating values: for (v <- scores.values) println(v)==>Tuple in Scala: val t = (1, 3.14, "Fred") val second = t._2 //Sets second to3.14, start indexing at 1! generating Tuple from Array: val symbols = Array("<", "-", ">") val counts = Array(2, 10, 2) val pairs = symbols.zip(counts) //yields: Array(("<", 2), ("-", 10), (">", 2))
相关文章
- Java集合总结系列2:Collection接口
- 总结day6 ---- set集合,基本类型的相互转化,编码,数据类型总结,循环时候不要动列表或者字典,深浅copy
- 总结:Java 集合进阶精讲2-ArrayList
- Scala学习教程笔记三之函数式编程、集合操作、模式匹配、类型参数、隐式转换、Actor、
- python基础知识3——基本的数据类型2——列表,元组,字典,集合
- Programming In Scala笔记-第十七章、Scala中的集合类型
- java基础小练习,1-打印一百次(1~10)的随机数,2-固定一个随机数(1~100),然后猜出他,3-定义以指定格式打印集合(ArrayList类型作为参数),使用{}括起来,使用@代替,分隔每个元素
- MySQL数据库数据类型之集合类型SET测试总结
- Struts2-整理笔记(四)Action生命周期、如何获取参数(3种)、集合类型参数封装
- Java集合总结系列2:Collection接口