Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demo for presentation given at TDC2014 SP. Simply paste it into a Scala Worksheet.
import scala.util.{Try, Success, Failure}
def div = (x:Int, y:Int) => x / y
div(4, 2)
type Enumerable[T] = () => () => Option[T]
def empty[T]:Enumerable[T] = {
() => () => None
}
def from[T](x:T): Enumerable[T] = () => {
var count = 0
() => {
if(count == 0){
count = count + 1
Some(x)
}
else None
}
}
def concat[T](xs:Enumerable[T], ys:Enumerable[T]): Enumerable[T] ={
val ysValues = ys()
val xsValues = xs()
() =>
() =>
xsValues() match {
case Some(x) => Some(x)
case None => ysValues() match{
case Some(y) => Some(y)
case None => None
}
}
}
def generate[T](seed:T, condition: T => Boolean, next: T => T): Enumerable[T] = {
if(!condition(seed)) () => () => None
else concat(from(seed), generate(next(seed), condition, next))
}
val enumerable = generate[Int](0, n => n < 3, n => n+1)
val enumerable2 = generate[Int](3, n => n < 6, n => n+1)
val enumerable3 = concat(enumerable, enumerable2)()
enumerable3()
enumerable3()
enumerable3()
enumerable3()
enumerable3()
enumerable3()
enumerable3()
enumerable3()
type Future[T] = ((Try[T]) => Unit) => Unit
def createFuture[T](value:T):Future[T] =
x => x(Success(value))
createFuture(10) {
case Success(x) => println(x)
}
type Observable[T] = ((Try[Option[T]]) => Unit) => Unit
def createObservable[T](value:T):Observable[T] =
x => {
x(Success(Some(value)))
x(Success(None))
}
def createObservableFromList[T](list:List[T]):Observable[T] =
x => {
for(v <- list) x(Success(Some(v)))
x(Success(None))
}
createObservable(10) {
case Success(Some(x)) => println(x)
case Success(None) => println("done")
}
createObservableFromList(List(1,2,3,4,5)) {
case Success(Some(x)) => println(x)
case Success(None) => println("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.