object Test {
// copy elements from a list to an array
val x = new Array[Int](5)
val y = List(1, 3, 5)
y.copyToArray(x, 0, 2)
x
// does it have definite size?
x.hasDefiniteSize
y.hasDefiniteSize
implicit class ListSafeTailInit[A](val list: List[A]) {
def tailOption: Option[List[A]] = {
if (list.isEmpty) None else Some(list.tail)
}
def initOption: Option[List[A]] = {
if (list.isEmpty) None else Some(list.init)
}
}
// safe head and tail
List[Int]().headOption.getOrElse(-9)
List[Int]().lastOption.getOrElse(-9)
// List[Int]().tail // UnsupportedOperationException
Nil.initOption // None
List[Int]().tailOption // None
// find first elem that satisfies predicate
List(1, 2, 3).find(_ > 1) // Some(2)
List(1, 2, 3, 4, 5).slice(0, 3) // from index 0 (inclusive) to 3 (exclusive)
List(1, 2, 3, 4, 5).span(_ < 3) // combines takeWhile and dropWhile
List(1, 2, 3, 4, 5).partition(_ % 2 == 0) // combines filter and filterNot
List(1, 2, 3, 4, 5).groupBy(x => if(x % 2 == 0) "even" else "odd") // returns a map
// string methods
val sb = new StringBuilder()
List(1, 2, 3).addString(sb, "'", ",", "'")
List(4, 5, 6).addString(sb, "'", ",", "'")
sb.toString() // '1,2,3''4,5,6'
List(1, 2, 3).mkString("'", ",", "'") // '1,2,3'
List(1, 2, 3).stringPrefix // List
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0)/1e9 + "s")
result
}
// collection views
// A view on a collection makes all transformations lazy, which makes it possible to combine multiple transformations into one.
// The non-lazy (eager) version:
time {
(1 to 1e7.toInt).map(_ + 2).map(x => {
if(x % 2 != 0) -x else x
}).sum
}
// The lazy version using a view
time {
(1 to 1e7.toInt).view.map(_ + 2).map(x => {
if(x % 2 != 0) -x else x
}).force.sum
}
}
Sunday, October 18, 2015
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment