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))