Skip to content

Instantly share code, notes, and snippets.

@seratch
Created November 16, 2011 11:07
Show Gist options
  • Save seratch/1369841 to your computer and use it in GitHub Desktop.
Save seratch/1369841 to your computer and use it in GitHub Desktop.
1
--------
val list = List("Scala", "http://scala-lang.org", "Java", "http://java.net/", "Haskell", "http://haskell.org/")
list.zipWithIndex.partition(_._2 % 2 == 0).zip.map(a => a._1._1 -> a._2._1)
2
---------
val list = List(1,2,1,3,2,4,4,2,4,3)
list.distinct
3
----------
val list = List(2,3,0,1,5,4)
list.map(a => a * a).sortWith(_ < _)
4
---------
val list = List(1, 2, 3, 4, 5)
for (i <- list; j <- list if j < i; k = i * j) yield (i, j, k)
5
----------
val h = List("name","lang","country")
val ds = List(("Andy","Scala","Japan"),("Brian","Python","America"),("Samir","Java","India"))
((h(0), h(1), h(2)) :: ds).foreach(r => println(r.productIterator.mkString(",")))
6
----------
case class Person(name: String, age: Int)
val people = List(
Person("Andy",34),
Person("Bob",18),
Person("Charles",45),
Person("Eric",13)
)
val (adults, minors) = people.partition(_.age >= 20)
7
-----------------
Range(1,100).par foreach { e => print(e +",") }
8
--------------
val input = List(1,2,3,"a","3",4)
val square = (a: Any) => a match {
case i: Int => Some(i*i)
case _ => None
}
input.flatMap{ a => square(a)}
9
---------------
case class Device(name: String)
case class User(name: String, devices: List[Device])
val users = List(
User("Andy", List(Device("iPhone"), Device("iPad"))),
User("Brian", List(Device("iPhone"))),
User("Charles", List(Device("Android"), Device("iPhone"))),
User("Dennis", List(Device("iPad"), Device("Android"), Device("iPad"))),
User("Eric", Nil)
)
users.flatMap(_.devices).groupBy(d => d).map(a => (a._1, a._2.size))
10
--------------
val emails = List(
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
)
emails.map(_.dropWhile(_ != '@').tail).groupBy(a => a).map(a => (a._1, a._2.size))
val extractDomainPart = (email: String) => email.dropWhile(_ != '@').tail
val sort = (ls: List[String]) => ls.sorted
val uniq = (ls: List[String]) => ls.groupBy(s => s).map(a => (a._1, a._2.size))
// sort is not required here
(sort andThen uniq)(emails.map(extractDomainPart))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment