Skip to content
Snippets Groups Projects
List.scala 979 B
Newer Older
Alexander Gehrke's avatar
Alexander Gehrke committed
package datastructures

enum List[+A]:
  case Nil
  case Cons(_head: A, _tail: List[A])

  def head: A = this match
Alexander Gehrke's avatar
Alexander Gehrke committed
    case Nil => sys.error("head of empty list")
    case Cons(a, _) => a

  /** removes the first element of a list and returns the rest */
Alexander Gehrke's avatar
Alexander Gehrke committed
  def tail: List[A] = ???

  /** returns all but the last element of a list */
Alexander Gehrke's avatar
Alexander Gehrke committed
  def init: List[A] = ???

  /** replaces the first element of a list */
Alexander Gehrke's avatar
Alexander Gehrke committed
  def setHead[AA >: A](head: AA): List[AA] = ???

  /** recurses through the list, combining elements with the given function
   *  Uncomment the annotation to enable checking for tail-recursiveness */
  //@annotation.tailrec
  final def foldLeft[B](z: B)(f: (B, A) => B): B = ???
object List:
  /** construct a list by passing elements
   *
   *  Remember: `apply` makes the object behave like a function,
   *    you can call it as `List(elem1, elem2,...)`
   **/
Alexander Gehrke's avatar
Alexander Gehrke committed
  def apply[A](as: A*): List[A] =
    if as.isEmpty then Nil
Alexander Gehrke's avatar
Alexander Gehrke committed
    else Cons(as.head, apply(as.tail: _*))