Skip to content

Instantly share code, notes, and snippets.

@xevix
Last active November 18, 2015 15:03
Show Gist options
  • Save xevix/bb2dbe874b4d0ea3506d to your computer and use it in GitHub Desktop.
Save xevix/bb2dbe874b4d0ea3506d to your computer and use it in GitHub Desktop.
Ruby'ish Scala
class Op[A]
case class EachOp[A]() extends Op[A]
case class CollectOp[A]() extends Op[A]
case class RubyIterator[B, A](iter: Iterator[A], op: Op[B]) {
def `do`(f: A => B): List[B] = {
op match {
case EachOp() =>
iter.foreach(f)
List.empty[B]
case CollectOp() =>
iter.map(f).toList
}
}
}
case class Foo[A](items: List[A]) {
def each() = {
mkIterator(EachOp[Unit]())
}
def collect() = {
mkIterator(CollectOp[A]())
}
private def mkIterator[B](op: Op[B]) = {
RubyIterator[B, A](items.iterator, op)
}
}
object main {
def main(args: Array[String]): Unit = {
val f = Foo(List(1,2,3))
// Ruby-like syntax
println("Each:")
f.each `do` { num =>
println(num)
}
println("")
println("Collect:")
val doubled = f.collect `do` { num: Int =>
num * 2
}
Foo(doubled).each `do` { num =>
println(num)
}
}
}
//Each:
//1
//2
//3
//
//Collect:
//2
//4
//6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment