Vectors are created analogously to Lists
val nums = New Vector(1,2,56,-87)
instead of List cons operator x :: xs use x +: xs or xs:+ x
Seq is a base class of List and Vector
Seq itself is a sub class of Iterable
| def factorial(x: Int) = (2 to x).reduceLeft(_ * _) |
| object ListFunctions extends App { | |
| val nums = List(2,-4,5,6,-3) | |
| // map function | |
| println(nums map (f => f > 0)) | |
| // filter function | |
| println(nums filter (f => f > 0)) | |
| object RunLengthEncoding extends App { | |
| val data = List("a","a", "a", "b","b", "a", "c", "c", "c") | |
| def pack[T](vals: List[T]): List[List[T]] = vals match { | |
| case Nil => Nil | |
| case x :: xs1 => | |
| val (first, rest) = vals span (y => y == x) | |
| first :: pack(rest) | |
| } |
| // Sum ints | |
| def sum(ints: List[Int]): Int = ints.foldLeft(0)((a,b) => a + b) | |
| def sum(ints:List[Int]): Int = ints.foldLeft(0)(_+_) | |
| // find average from a list of Double | |
| def average(list: List[Double]): Double = | |
| list.foldLeft(0.0)(_+_) / list.foldLeft(0.0)((r,c) => r+1) | |
| def average(list: List[Double]): Double = list match { |
| def sum(x: Int)(y: Int)(z: Int) = x + y + z | |
| val curriedWithMultipleArguments = sum _ | |
| val addToNine = curriedWithMultipleArguments(4,5) | |
| addToNine(3) |
Vectors are created analogously to Lists
val nums = New Vector(1,2,56,-87)
instead of List cons operator x :: xs use x +: xs or xs:+ x
Seq is a base class of List and Vector
Seq itself is a sub class of Iterable
| val a = 1 //> a : Int = 1 | |
| val b = 2 //> b : Int = 2 | |
| // Common mistakes with pattern matching | |
| // the lower case variable pattern needs backwards quotes to work. | |
| def oneOrTwo(i: Int): String = i match { | |
| case `a` => "One!" | |
| case `b` => "Two!" | |
| } //> oneOrTwo: (i: Int)String |
| GET /clients/:id controllers.Clients.show(id: Long) |
| cursor = db.students.aggregate( | |
| [ { "$unwind": "$scores" }, | |
| {"$match": {"scores.type": "homework"}}, | |
| {"$group": { '_id':'$_id' , 'minitem': {'$min': "$scores.score" }}} | |
| ] ); | |
| db.students.update({'_id':19},{'$pull':{'scores':{'score':49.43132782777443}}}) |
| private class Article { | |
| private final String title; | |
| private final String author; | |
| private final List<String> tags; | |
| private Article(String title, String author, List<String> tags) { | |
| this.title = title; | |
| this.author = author; | |
| this.tags = tags; |