Trees - University of Pennsylvania:树-宾夕法尼亚大学.pptVIP

  • 4
  • 0
  • 约8.22千字
  • 约 17页
  • 2018-04-17 发布于江西
  • 举报

Trees - University of Pennsylvania:树-宾夕法尼亚大学.ppt

Trees - University of Pennsylvania:树-宾夕法尼亚大学.ppt

Sequences and for loops Simple for loops A for loop is used to do something with every element of a sequence scala for (i - 2 to 5) println(i + squared is + i * i) 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 scala for (i - supercalifragilisticexpealedoceous) print(i + -) s-u-p-e-r-c-a-l-i-f-r-a-g-i-l-i-s-t-i-c-e-x-p-e-a-l-e-d-o-c-e-o-u-s- scala var sum = 0; for (i - 1 to 100) sum = sum + i sum: Int = 5050 So, what is a “sequence”? * Ranges are sequences scala 1 to 5 res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5) scala 1 until 5 res1: scala.collection.immutable.Range = Range(1, 2, 3, 4) scala Range(1, 5) res2: scala.collection.immutable.Range = Range(1, 2, 3, 4) scala 1 to 5 by 2 res3: scala.collection.immutable.Range = Range(1, 3, 5) scala 1 until 5 by 2 res4: scala.collection.immutable.Range = Range(1, 3) scala Range(1, 5, 2) res5: scala.collection.immutable.Range = Range(1, 3) scala for (i - Range(1, 5)) print(i) 1234 * Arrays are sequences scala Array(2, 3, 5, 7, 11, 13) res0: Array[Int] = Array(2, 3, 5, 7, 11, 13) scala Array(one, two, three) res1: Array[String] = Array(one, two, three) scala new Array[Int](8) res2: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0) scala new Array[String](4) res3: Array[String] = Array(null, null, null, null) scala res3(1) = one scala res3(0) = zero scala res3 res6: Array[String] = Array(zero, one, null, null) * Vectors are sequences scala Vector(2, 3, 5, 7, 11, 13) res0: scala.collection.immutable.Vector[Int] = Vector(2, 3, 5, 7, 11, 13) scala Vector(one, two, three) res1: scala.collection.immutable.Vector[String] = Vector(one, two, three) How are Arrays and Vectors different? Arrays are mutable: You can change their contents You saw this on the previous slide Vectors are immutable: You cannot change them How are Arrays and Vectors similar? You can index into them (starting from zero), to find a value scala res1(0) res12: String = one * Lists are sequences scala List(3

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档