Advertisement
karol_dziachan

SimpleTask__Scala__

Oct 7th, 2020 (edited)
2,038
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.15 KB | None | 0 0
  1. // Karol Dziachan
  2.  
  3. //task1
  4.  
  5. def flatten[A] (xs:List[List[A]]) : List[A] =
  6.   if(xs == Nil) throw new Exception("Empty list")
  7.   else if (xs.length == 1) xs.head
  8.    else xs.head ::: flatten(xs.tail)
  9.  
  10.  
  11. flatten(List(List(1,2,3), List(4,5,6), List(7,8,9))) == List(1,2,3,4,5,6,7,8,9)
  12. flatten(List(List(), List(1,2,3))) == List(1,2,3)
  13. flatten(List(List(4,5,6), List())) == List(4,5,6)
  14. flatten(List())
  15.  
  16.  
  17. //task2
  18.  
  19.  
  20.  
  21. def count [A] (x: A, xs: List[A]) : Int =
  22.   if(xs == Nil) throw new Exception("empty list")
  23.   else if(xs.tail == Nil)
  24.     if(xs.head == x) 1
  25.       else 0
  26.   else if(xs.head == x) 1+count(x: A, xs.tail)
  27.   else count(x: A, xs.tail)
  28.  
  29. count ('a', List('a','l','a')) == 2
  30. count ('a', List('a','l','a', 'a', 'a', 'm', 'a')) == 5
  31. count ('a', List('l')) == 0
  32. count ('a', List('a')) == 1
  33. count(1, List(1,2,4,1,3,2,1)) == 3
  34. count ('a', List())
  35.  
  36.  
  37.  
  38. //task3
  39.  
  40. def replicate [A] (x: A, n: Int): List[A] =
  41.    if(n==1) List(x)
  42.     else if(n==0) throw new Exception("Nothing")
  43.    else List(x)::: replicate(x, n-1)
  44.  
  45.  
  46.  
  47. replicate("la", 3) == List("la", "la", "la")
  48. replicate("la", 1) == List("la")
  49. replicate("", 3) == List("", "", "")
  50. replicate("la", 0)
  51. replicate("", 0)
  52.  
  53. //task4
  54.  
  55.  
  56. def sqrList (xs: List[Int]): List[Int] =
  57.   if(xs == Nil ) throw new Exception("empty list")
  58.   else if(xs.tail != Nil) ((List(xs.head*xs.head) ::: sqrList(xs.tail)))
  59.     else if (xs.head != Nil ) List(xs.head*xs.head)
  60.   else   xs
  61.  
  62. sqrList(List(1,2, 3, (-4)))
  63. sqrList(List(1,2,3,4,5))
  64. sqrList(List((-1), 2, 3, 4, (-5)))
  65. sqrList(List())
  66.  
  67. //task5
  68.  
  69. def palindrome[A] (xs: List[A]): Boolean =
  70.   if(xs==Nil) throw new Exception("Empty list")
  71. else
  72.   xs==xs.reverse
  73.  
  74. palindrome(List("a", "l", "a"))
  75. palindrome(List("A", "l", "a"))
  76. palindrome(List("k", "a", "j", "a", "k"))
  77. palindrome(List("k", "a", "r", "o", "l"))
  78. palindrome(List())
  79.  
  80. //task6
  81.  
  82. def listLength[A](xs: List[A]): Int =
  83.   if(xs == Nil) throw new Exception ("empty list")
  84.   else if (xs.tail != Nil) 1+listLength(xs.tail)
  85.   else 1
  86.  
  87. listLength(List(1,2,3,4,5))
  88. listLength(List("k", "a", "r", "o", "l"))
  89. listLength(List("mother"))
  90. listLength(List("mother", "father"))
  91. listLength(List())
  92.  
  93.  
  94.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement