Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.{OutputStream, InputStream}
import Skandal._
import scala.annotation.tailrec
import scala.collection.mutable.LazyBuilder
import scala.collection.generic.CanBuildFrom
import scala.collection.mutable.Builder
import scala.collection.SeqLike
import scala.collection.generic.GenericTraversableTemplate
import scala.collection.generic.GenericCompanion
object Mustivar {
def main(args: Array[String]): Unit = {
val set: Set[Int] = Lisst(1,2,3,4).map{ 2 * }(scala.collection.breakOut)
println(set)
val levar = Lisst(1,2,3)
println{
Set(1,2,3).to[Lisst]
}
}
}
object Lisst extends GenericCompanion[Lisst]{
override def apply[T](t: T*): Lisst[T] = t.reverse.foldLeft(ListNil: Lisst[T]){ _ append _ }
override def newBuilder[T]: Builder[T, Lisst[T]] = new Builder[T, Lisst[T]]{
private var acc: List[T] = Nil
def +=(t: T) = {
acc ::= t
this
}
def clear() = acc = Nil
def result() = acc.foldLeft(ListNil: Lisst[T]){ _ append _ }
}
implicit def builder[T, U]: CanBuildFrom[Nothing, U, Lisst[U]] = new CanBuildFrom[Nothing, U, Lisst[U]]{
def apply() = newBuilder
def apply(that: Nothing) = newBuilder
}
}
sealed trait Lisst[+T] extends Traversable[T] with GenericTraversableTemplate[T, Lisst] {
override def companion = Lisst
override def isEmpty = this eq ListNil
override def head: T = this match {
case ListNil => throw new NoSuchElementException
case ListCons(head, _) => head
}
override def tail: Lisst[T] = this match{
case ListNil => throw new NoSuchElementException
case ListCons(_, tail) => tail
}
def append[U>:T](elem: U) = elem::this
def ::[U>:T](elem: U): Lisst[U] = ListCons(elem, this)
@tailrec override final def foreach[U](f: T => U): Unit = if(!isEmpty) {
f(head)
tail.foreach(f)
}
def reverse = {
def inner(acc: Lisst[T], rem: Lisst[T]): Lisst[T] = rem match {
case ListNil => acc
case ListCons(head, tail) => inner(head::acc, tail)
}
inner(ListNil, this)
}
def iterator = new Iterator[T]{
private[this]var current = Lisst.this
def hasNext = current ne ListNil
def next = {
val tmp = head
current = current.tail
tmp
}
}
}
case class ListCons[T](override val head: T, override val tail: Lisst[T]) extends Lisst[T]
case object ListNil extends Lisst[Nothing]
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.