Last active
December 5, 2018 00:10
-
-
Save vicsstar/5b4044dd647c39e22a9358636f821fb0 to your computer and use it in GitHub Desktop.
Basic scala list-like implementation.
This file contains 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
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