Skip to content

Instantly share code, notes, and snippets.

@vicsstar
Last active December 5, 2018 00:10
Show Gist options
  • Save vicsstar/5b4044dd647c39e22a9358636f821fb0 to your computer and use it in GitHub Desktop.
Save vicsstar/5b4044dd647c39e22a9358636f821fb0 to your computer and use it in GitHub Desktop.
Basic scala list-like implementation.
object Main {
type T = Any
trait Listy[T] {
val value: T
def isEmpty: Boolean
def head: Option[T]
def tail: Listy[T]
def filter(predicate: T => Boolean): Listy[T] = {
if (predicate(value)) ListyImpl(value, tail.filter(predicate)) else tail
}
def find(predicate: T => Boolean): Option[T] = {
if (predicate(value)) Some(value) else {
if (tail.isEmpty) None
else tail.find(predicate)
}
}
implicit def ::(value: T): Listy[T] = ListyImpl(value, if (tail.isEmpty) Nily else tail)
}
case object Nily extends Listy[T] {
val value = null
def isEmpty = true
def head = throw new java.util.NoSuchElementException("head of an empty list")
def tail = throw new UnsupportedOperationException("tail of an empty list")
}
case class ListyImpl[T](value: T, rest: Listy[T]) extends Listy[T] {
def isEmpty = false
def head = Some(value)
def tail = rest
}
def main(args: Array[String]): Unit = {
// convert to list using single operator.
val list = 1 :: Nily
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment