Skip to content

Instantly share code, notes, and snippets.

@huynhjl
huynhjl / gist:599089
Created September 27, 2010 14:10 — forked from kbloom/gist:580157
Generators with continuations
import scala.util.continuations._
class Generator[A] extends Iterator[A] with (A => Unit @ suspendable) {
private var a: Option[A] = None
private var k: Option[Unit => Unit] = None
def next = {
val a0 = a.get
val k0 = k.get
a = None
@huynhjl
huynhjl / LookAheadIterator.scala
Created September 10, 2010 14:18
LookAheadIterator
/**
* An iterator that allows retrieving elements ahead without advancing the iterator.
*/
class LookAheadIterator[T](underlying:Iterator[T]) extends BufferedIterator[T] {
private val queue = collection.mutable.Queue[T]()
/**
* Returns a new iterator to read ahead element.
* Elements from underlying are queued so that they can be returned by the
// Borrowed from
// http://stackoverflow.com/questions/3102872/what-is-the-fastest-way-to-sum-a-collection-in-scala/3103800#3103800
def time[F](f: => F) = {
val t0 = System.nanoTime
val ans = f
printf("Elapsed: %.3f\n",1e-9*(System.nanoTime-t0))
ans
}
import scala.annotation._
val l = 0 until 30 toList
def div(i:Int) = i / 2
def cluster[T,U](xs:Seq[T], f:T => U): Seq[(U, Seq[T])] = {
@tailrec
def tr_cluster(acc: Seq[(U, Seq[T])], xs:Seq[T]): Seq[(U, Seq[T])] = {
if (xs.isEmpty) {
@huynhjl
huynhjl / Yield.scala
Created February 7, 2010 05:19
code with scalac -print output at the end
// The continuation code is from an answer by Rich posted at StackOverflow
// http://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182
import scala.continuations._
import scala.continuations.ControlContext.{shift,reset}
sealed trait Iteration[+R]
case class Yield[+R](result: R, next: () => Iteration[R]) extends Iteration[R]
case object Done extends Iteration[Nothing]
// The continuation code is from an answer by Rich posted at StackOverflow
// http://stackoverflow.com/questions/2201882/implementing-yield-yield-return-using-scala-continuations/2215182#2215182
// The printClass example is from this question http://stackoverflow.com/questions/2137619/scala-equivalent-to-python-generators
import scala.continuations._
import scala.continuations.ControlContext.{shift,reset}
sealed trait Iteration[+R]
case class Yield[+R](result: R, next: () => Iteration[R]) extends Iteration[R]
def yieldClass2(clazz:Class[_]): Iterator[Class[_]] = {
import scala.collection.{Iterator => I}
clazz match {
case null => I.empty
case _ =>
val interfaces = clazz.getInterfaces map { yieldClass2 } reduceLeft (_ ++ _)
I.single(clazz) ++ yieldClass2(clazz.getSuperclass) ++ interfaces
}
}
import scala.xml.pull._
import scala.xml.UnprefixedAttribute
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.Stack
import scala.io.Source
class Joint(name:String) {
val joints = ListBuffer[Joint]()
def addJoint(joint:Joint) {
joints += joint