Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //zadanie 1
- class GenericCellMut[+T] (var x: T) {
- }
- //a)
- //Modyfikowalne strutury powinny byÄ inwariantne
- //Bo majÄ c GenericCellMut[Int] mĂłgĹbym traktowaÄ jÄ jako
- //GenericCellMut[Any] bo Int <: Any ale wtedy mĂłgĹbym rĂłwnie dobrze
- //DaÄ tam String bo String <: Any.
- //b)
- //Albo robimy to inwariantne albo struktura zostaje niemodyfikowalna
- //zadanie 2
- abstract class Sequence[+A] {
- def append[B >: A](x: Sequence[B]):Sequence[A] //zapewniamy, Ĺźe A jest podtypem B i w tej funkcji zawsze bezpiecznie moĹźemy uĹźyÄ A w kontekĹcie B
- }
- trait Function1[-T1, +R] { //kontrawariantość argumentów i kowariantość wyników
- def apply(t : T1) : R
- ...
- }
- //Scala definuje trait Function1 jako posiadajÄ cÄ dwa parametry typu
- //Function1[GParent,Child] <: Function1[Parent,Parent]
- //W naszej funkcji powiedzieliĹmy Ĺźe T jest kowariwantne i Ĺźe bierze parametr x typu T
- //WiÄc w pewnym momencie moĹźemy mieÄ jakieĹ S <: T i wtedy instancjÄ GenericCellMut[T]
- //MoglibyĹmy zastÄ piÄ GenericCellMut[S] ale wtedy wszystkie metody biorÄ ce T nie mogÄ
- //byÄ zastÄ pione przez S bo to co wyĹźej
- //zadanie 3
- class Queue[T] private (val l1: List[T], val l2: List[T]) {
- class EmptyException(message: String) extends Exception(message)
- def this() = this(Nil, Nil)
- def enqueue(elem: T) = {
- (l1, l2) match {
- case (Nil, Nil) => new Queue(List(elem), Nil)
- case (lt1, lt2) => new Queue(l1, elem :: l2)
- }
- }
- def dequeue() = {
- (l1, l2) match {
- case (Nil, Nil) => this
- case (List(_), l) => new Queue(l.reverse, Nil)
- case (_ :: t, l) => new Queue(t, l)
- }
- }
- def first() =
- (l1, l2) match {
- case (Nil, Nil) => throw new EmptyException("Kolejka jest pusta!")
- case (h :: _, _) => h
- case _ => throw new EmptyException("B³šd implementacji!")
- }
- def isEmpty = l1 == Nil
- }
- //zadanie 4
- import scala.collection.mutable._
- def copy[T](dest: Seq[T], src: Seq[T]): = { // reprezentuje ciągi - kolekcje o określonym porządku.
- var i = 0
- src foreach {
- el =>
- dest.update(i, el) //update zwraca kopie seq ze zmienionym jedynym elementem
- i += 1
- }
- }
- val a = Seq(1,2,3)
- val b = Seq(3,3,3,4,5)
- copy(b,a)
- b.toString //res2: String = ArrayBuffer(1, 2, 3, 4, 5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement