Advertisement
Guest User

Untitled

a guest
Oct 17th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 5.21 KB | None | 0 0
  1. import scala.annotation.tailrec
  2.  
  3. def sum(l: Int*) : Int = {
  4.   @tailrec
  5.   def inner(xs: Seq[Int], acc: Int): Int = {
  6.     xs match {
  7.       case Seq() => acc
  8.       case Seq(head ,tail@_*) => inner(tail, head + acc)
  9.     }
  10.     //if (xs.isEmpty) acc
  11.     //inner(xs.tail, acc + xs.head)
  12.   }
  13.   def inner2(l: List[Int], acc: Int): Int = {
  14.     l match {
  15.       case Nil => acc
  16.       case head :: tail => inner2(tail, head + acc)
  17.     }
  18.   }
  19.   inner(l, 0)
  20. }
  21.  
  22. sum(1, 2, 3)
  23. sum(List(1, 2, 3): _*)
  24.  
  25. //**********************************************************
  26.  
  27. val map = Map(1 -> "one", 2 -> "two")
  28. for ((num, str) <- map) {
  29.   //unit
  30. }
  31. for ((num, str) <- map) yield {
  32.   s"$num -> $str"
  33. }
  34.  
  35. //один перенос строки -> ok
  36. 1+
  37. 2
  38. +3
  39.  
  40. //fail, два переноса строки, интерпретируется как точка с запятой
  41. """
  42. 1+
  43. 2+
  44.  
  45. 3
  46. """
  47.  
  48. val set = Set(1, 2, 3)
  49. val list = List(1, 2, 3)
  50. for {
  51.   elem <- set
  52.   if elem % 2 != 0
  53.   inc = elem + 1
  54.   elem2 <- list
  55. } yield inc + elem2
  56.  
  57. // *****************************************************************
  58.  
  59. val a = Array(1, 2, 3)
  60. a(1) = 4
  61. a.update(1, 4)
  62. a.toSeq
  63.  
  64. import scala.collection.JavaConverters._
  65. import java.util
  66. val javaCollection: util.List[Int] = Seq(1, 2, 3).asJava
  67. Seq(1,2,3).asJavaCollection
  68. javaCollection.asScala
  69. for (i <- javaCollection.asScala) yield i + 1
  70.  
  71. import scala.collection.JavaConversions._
  72.  
  73. for (i <- javaCollection) yield i + 1
  74.  
  75. // ***************************************************************
  76. //function literals
  77. val inc1 = (x: Int) => x + 1
  78. val inc2: (Int => Int) = (x => x + 1)
  79. val inc3: (Int => Int) = _ + 1 //x$1 = x$1 + 1
  80. val inc4 = (_: Int) + 1
  81.  
  82. def inc(x: Int) = x + 1
  83. val inc5: Int => Int = inc
  84. val inc6 = inc _
  85.  
  86. val inc7: Int => Int = {
  87.   case i => i + 1
  88. }
  89.  
  90. val add1 = (x: Int, y: Int) => x + y
  91. val add2: (Int, Int) => Int = _ + _ // (x$1, x$2) => x$1 + x$2
  92. // _ - всегда новый параметр
  93. val add3: (Int, Int) => Int = (x, y) => x + y
  94.  
  95. //high-order functions
  96. def map(list: List[Int], map: Int => Int): List[Int] = {
  97.   for (elem <- list) yield map(elem)
  98. }
  99.  
  100. map(List(1, 2, 3), inc3)
  101. map(List(1, 2, 3), x => x * 2)
  102.  
  103. // **************************************************************
  104. val list1 = List(1, 2, 3)
  105. list1.map(_ + 1)
  106. list1.filter(_ % 2 == 0)
  107. list1.flatMap(x => Seq.fill(10)(x)) // fill 10 раз элемент x
  108. List(List(1), List(2)).flatten
  109. List(1, 2, 3).flatten // не скомпилируется
  110.  
  111. list1.flatMap(x => Seq.fill(x)(x))
  112. list1.map(x => Seq.fill(x)(x)).flatten
  113.  
  114. List(1, 2, 3).foldLeft(0)(_ + _) // последовательные скобки нужны для вывода типов
  115. //вторая скобка уже знает о типе параметра из первой скобки
  116. def foo(x: Int)(y: Int) = x + y
  117. val z: Int => Int = foo(1)
  118.  
  119. def go(x: Int, y: Int) = x + y
  120. val z1: Int => Int = go(1, _)
  121.  
  122. // *********************************************************
  123. //partial functions
  124.  
  125. val partalFunction: PartialFunction[Int, Int] = {
  126.   case x: Int if x % 2 == 0 => x / 2
  127. }
  128.  
  129. partalFunction(2)
  130. partalFunction(3) //MatchError
  131. partalFunction.isDefinedAt(3)
  132.  
  133. val inc7v2: Int => Int = {
  134.   case i => i + 1
  135. }
  136.  
  137. def isOdd(x: Int): Boolean = x % 2 == 0
  138. def isEven(x: Int): Boolean = x % 2 != 0
  139.  
  140. list.find(_ == 2) //optional
  141. list.indexWhere(_ == 3)
  142. list.takeWhile(isEven)
  143. list.dropWhile(isEven)
  144. list.partition(isEven)
  145.  
  146. list.groupBy(_ % 3)
  147. list.collect(partalFunction)
  148. list.filter(partalFunction.isDefinedAt).map(partalFunction)
  149.  
  150. // ***********************************************************
  151.  
  152. class B
  153.  
  154. //primary constructor
  155. class C(x: Int) {
  156.   val y = x + 1
  157.   def foo: Unit = {
  158.     print(x)
  159.   }
  160. }
  161.  
  162. new C(123)
  163.  
  164. class A(x: Int) {
  165.   def this(s: String) {
  166.     //val x = ()... // так нельзя
  167.     this(s.toInt) //всегда первая инструкция
  168.   }
  169.   val y = x + 1
  170.   def foo: Unit = {
  171.     print(x)
  172.   }
  173. }
  174.  
  175. class Base(x: Int)
  176. class D(x: Int) extends Base(x + 1) {
  177. }
  178.  
  179. class E extends Base(1) {}
  180. new E
  181. def foo() = 1
  182. def foo1 = 1
  183. foo()
  184. foo
  185. //foo1() // нельзя
  186. foo1 // скобок нет - нет side-effects
  187.  
  188.  
  189. trait BaseTrait {
  190.   def foo = 1
  191.   val y: Int = 1
  192.   var z: Int = 3
  193. }
  194. //отличия от класса - 1) нет конструктора 2) вызовы super (линеаризация и прочие прелести)
  195. //First, a trait cannot have any “class” parameters, i.e., parameters passed to the primary constructor of a class. In other words, although you could define a class like this: class Point(x: Int, y: Int)
  196. //The other difference between classes and traits is that whereas in classes, super calls are statically bound, in traits, they are dynamically bound. If you write “super.toString” in a class, you know exactly which method implementation will be invoked. When you write the same thing in a trait, however, the method implementation to invoke for the super call is undefined when you define the trait.
  197.  
  198. //есть множественное наследование трейтов
  199.  
  200. class F extends Base(1) with BaseTrait with Traversable[Int] {}
  201.  
  202. object A extends BaseTrait {
  203.   override def foo = 1
  204. }
  205. A.foo
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement