Advertisement
Guest User

spławik 10

a guest
Jan 8th, 2015
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.35 KB | None | 0 0
  1. //zadanie 1
  2. class GenericCellMut[+T] (var x: T) {
  3. }
  4. //a)
  5. //Modyfikowalne strutury powinny być inwariantne
  6. //Bo mając GenericCellMut[Int] mógłbym traktować ją jako
  7. //GenericCellMut[Any] bo Int <: Any ale wtedy mógłbym równie dobrze
  8. //Dać tam String bo String <: Any.
  9. //b)
  10. //Albo robimy to inwariantne albo struktura zostaje niemodyfikowalna
  11.  
  12. //zadanie 2
  13. abstract class Sequence[+A] {
  14.   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
  15. }
  16.  
  17. trait Function1[-T1, +R] {  //kontrawariantość argumentów i kowariantość wyników
  18.   def apply(t : T1) : R
  19.   ...
  20. }
  21. //Scala definuje trait Function1 jako posiadającą dwa parametry typu
  22. //Function1[GParent,Child] <: Function1[Parent,Parent]
  23. //W naszej funkcji powiedzieliśmy że T jest kowariwantne i że bierze parametr x typu T
  24. //Więc w pewnym momencie możemy mieć jakieś S <: T i wtedy instancję GenericCellMut[T]
  25. //Moglibyśmy zastąpić GenericCellMut[S] ale wtedy wszystkie metody biorące T nie mogą
  26. //być zastąpione przez S bo to co wyżej
  27.  
  28. //zadanie 3
  29. class Queue[T] private (val l1: List[T], val l2: List[T]) {
  30.   class EmptyException(message: String) extends Exception(message)
  31.  
  32.   def this() = this(Nil, Nil)
  33.  
  34.   def enqueue(elem: T) = {
  35.     (l1, l2) match {
  36.       case (Nil, Nil) => new Queue(List(elem), Nil)
  37.       case (lt1, lt2) => new Queue(l1, elem :: l2)
  38.     }
  39.   }
  40.  
  41.   def dequeue() = {
  42.     (l1, l2) match {
  43.       case (Nil, Nil) => this
  44.       case (List(_), l) => new Queue(l.reverse, Nil)
  45.       case (_ :: t, l) => new Queue(t, l)
  46.     }
  47.   }
  48.  
  49.   def first() =
  50.     (l1, l2) match {
  51.       case (Nil, Nil) => throw new EmptyException("Kolejka jest pusta!")
  52.       case (h :: _, _) => h
  53.       case _ => throw new EmptyException("B³šd implementacji!")
  54.     }
  55.  
  56.   def isEmpty = l1 == Nil
  57. }
  58.  
  59. //zadanie 4
  60. import scala.collection.mutable._
  61. def copy[T](dest: Seq[T], src: Seq[T]): = { // reprezentuje ciągi - kolekcje o określonym porządku.
  62.   var i = 0
  63.   src foreach {
  64.     el =>
  65.       dest.update(i, el) //update zwraca kopie seq ze zmienionym jedynym elementem
  66.       i += 1
  67.   }
  68.  }
  69.  val a = Seq(1,2,3)
  70.  val b = Seq(3,3,3,4,5)
  71.  copy(b,a)
  72.  b.toString //res2: String = ArrayBuffer(1, 2, 3, 4, 5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement