Created
August 19, 2013 11:24
-
-
Save adamretter/6268095 to your computer and use it in GitHub Desktop.
Attempting to implement custom Scala Collection, this code seems to cause the Scala 2.10.2 compiler into an infinite loop :-(
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.collection.generic.{GenericCompanion, GenericTraversableTemplate, SeqFactory} | |
import scala.collection.mutable.{ArrayBuffer, Builder} | |
class MyCollectionBuilder[A] extends Builder[A, MyCollection[A]] { | |
val data = ArrayBuffer[A]() | |
def +=(elem: A) = { | |
data += elem | |
this | |
} | |
def clear() { | |
data.clear() | |
} | |
def result() = ::(data.head, ::(data.tail.head, ::(data.tail.tail.head, MyCollectionNil))) //TODO recurse! only does 3 at the moment | |
} | |
abstract class MyCollection[+A] extends Seq[A] | |
with GenericTraversableTemplate[A, MyCollection] { | |
override def companion: GenericCompanion[MyCollection] = MyCollection | |
def apply(idx: Int) = if(idx == 1) head else tail(idx - 1) | |
def length = if(isEmpty) 0 else tail.length + 1 | |
def iterator = new Iterator[A] { | |
var first = true | |
var current = this | |
def hasNext = { | |
current.isEmpty | |
} | |
def next() = { | |
val next = current.tail | |
current.head | |
current = next | |
} | |
} | |
} | |
object MyCollection extends SeqFactory[MyCollection] { | |
def newBuilder[A] = new MyCollectionBuilder[A]() | |
} | |
final case class ::[B](val hd: B, val tl: MyCollection[B]) extends MyCollection[B] { | |
override def head : B = hd | |
override def tail : MyCollection[B] = tl | |
override def isEmpty: Boolean = false | |
} | |
case object MyCollectionNil extends MyCollection[Nothing] { | |
} | |
object Main extends App { | |
val c = ::("hello", ::("world", ::("again", MyCollectionNil))) | |
c match { | |
case head :: tail => | |
println(s"head[$head] tail[$tail]") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment