MI-PSL-8 Flashcards
What are main features of collection List?
List je základní datovou strukturou funkcionálního programování. Jejich hlavní výhody:
jsou immutable
mají rekurzivní strukturu
je předdefinováno velké množství funkcí pro práci s listy
Do write the definition of the class which defines the node of the list.
final case class ::B extends List[B] {def isEmpty = false}
Do write the definition of Nil.
case object Nil extends List[Nothing] {
override def isEmpty = true
override def head: Nothing =
throw new NoSuchElementException(“empty list”)
override def tail: List[Nothing] =
throw new UnsupportedOperationException
(“empty list”)
Do write the concatenation function of the class List.
def ::[B >: A] (x: B): List[B] = new scala.collection.immutable.::(x, this)
What are the elementary operations of list by which the other can be defined.
funkce:
head - vrací první prvek listu
tail - vrací zbytek listu
isEmpty - indikuje zda je seznam prázdný
Write the definition of method List.length
def length: Int = this match { case Nil => 0 case x :: xs => 1 + xs.length }
Write the definition of method List.init
def init: A = this match { case Nil => error("Nil.last") case x :: Nil => Nil case x :: xs => x :: xs.init }
Write the definition of method List.last
def last: A = this match { case Nil => error("Nil.last") case x :: Nil => x case x :: xs => xs.last }
Write the definition of method List.take
def take(n: Int): List[A] =
if (n == 0 || isEmpty) Nil
else head :: tail.take(n-1)
Write the definition of method List.drop
def drop(n: Int): List[A] =
if (n == 0 || isEmpty) this
else tail.drop(n-1)
Write the method which enables list subscripting.
def apply(n: Int): A = drop(n).head
Write the method which enables list concatenation.
def :::[B >: A](prefix: List[B]): List[B] = prefix match { case Nil => this case x :: xs => this.:::(xs).::(x) }
Write the definition of method List.map
def map[B](f: A => B): List[B] = this match { case Nil => this case x :: xs => f(x) :: xs.map(f) }
Write the definition of method List.foreach
def foreach(f: A => Unit) { this match { case Nil => () case x :: xs => f(x); xs.foreach(f) } }
Write the definition of method List.filter
def filter(p: A => Boolean): List[A] = this match { case Nil => this case x :: xs => if (p(x)) x :: xs.filter(p) else xs.filter(p) }