embracing-nondeterminism-code/src/main/scala/green/thisfieldwas/embracingnondeterminism/extractables/seq/List.scala

37 lines
984 B
Scala

package green.thisfieldwas.embracingnondeterminism.extractables.seq
sealed trait List[+A] extends Extractable[A] {
def head: A
def tail: List[A]
def ::[B >: A](x: B): List[B] = new ::(x, this)
// satisfies non-empty Seq if present
// but Seq can be empty by definition, so you have to blindly trust that it
// has at least one element as this doesn't free you from Seq's void effect
def extract: Seq[A] = {
def go(list: List[A]): Seq[A] = list match {
case h :: t => h +: go(t)
case Nil => Seq.empty
}
Seq(head) ++ go(tail)
}
// satisfies true if present
// satisfies false if void
// does not indicate if more instances after head
def isExtractable: Boolean = this.isInstanceOf[::[A]]
}
case class ::[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing] {
def head: Nothing = throw new NoSuchElementException("Nil.head")
def tail: Nothing = throw new NoSuchElementException("Nil.tail")
}