Skip to content

Instantly share code, notes, and snippets.

View daithiocrualaoich's full-sized avatar

Daithi O Crualaoich daithiocrualaoich

View GitHub Profile
@daithiocrualaoich
daithiocrualaoich / gist:1189097
Created September 2, 2011 16:37
Scala Collections Pimp to add distinctBy(hash: ... => ...) for hash filterings
implicit def seq2Distinct[T, C[T] <: Seq[T]](tees: C[T]) = new {
import collection.generic.CanBuildFrom
import collection.mutable.{HashSet => MutableHashSet}
def distinctBy[S](hash: T => S)(implicit cbf: CanBuildFrom[C[T],T,C[T]]): C[T] = {
val builder = cbf()
val seen = MutableHashSet[S]()
for (t <- tees) {
if (!seen(hash(t))) {
@daithiocrualaoich
daithiocrualaoich / gist:1119974
Created August 2, 2011 10:22
Pimping scala.collections
implicit def iterable2Cross[T, C[T] <: Iterable[T]](tees: C[T]) = new {
import collection.generic.CanBuildFrom
def cross[S](esses: Iterable[S])(implicit cbf: CanBuildFrom[C[(T,S)],(T,S),C[(T,S)]]): C[(T,S)] = {
val builder = cbf()
val rst = for (t <- tees; s <- esses) yield (t, s)
rst foreach { builder += }
builder.result
@daithiocrualaoich
daithiocrualaoich / gist:845479
Created February 26, 2011 18:37
scala.io.Source is slow
> test
...
[info] Test Starting - BenchmarksTest: SourceBenchmark
Mean: 392.100000
StdDev: 5.022947
[info] Test Succeeded - BenchmarksTest: SourceBenchmark
[info] Test Starting - BenchmarksTest: InputStreamBenchmark
Mean: 69.610000
@daithiocrualaoich
daithiocrualaoich / gist:830846
Created February 17, 2011 02:43
Lazy evaluation of closures during object construction
scala> def test = { println("Evaluating"); "test" }
test: java.lang.String
scala> case class TestClass(s: String) { override def toString = "overrided so the REPL doesn't coerse evaluation of s" }
defined class TestClass
scala> val t = TestClass(test)
Evaluating
t: TestClass = overrided so the REPL doesn't coerse evaluation of s
@daithiocrualaoich
daithiocrualaoich / gist:661305
Created November 3, 2010 16:25
Anonymous functions with tuple parameters
scala> val l = List((1,2), (2,3))
l: List[(Int, Int)] = List((1,2), (2,3))
scala> l map { case (i, j) => i+j }
res5: List[Int] = List(3, 5)
scala> import Function.tupled
import Function.tupled
scala> l map tupled { (i, j) => i + j }
trait InMainThread {
private val handler = new Handler
def mainThread(block: => Unit) {
handler.post(new Runnable {
def run { block }
})
}
}