Skip to content
Jaejin Gim edited this page Aug 6, 2016 · 3 revisions

Range

어떤 시작값부터 마지막 값에 이르는 수열

Range 와 NumericRange

  • Range 는 시작값과 종료값 그리고 0이 아닌 증분값을 가지는 Int 형의 수열을 제공
  • NumericRange는 타입추론을 통해 Range 보다 더 generic 한 수열을 제공하며 반드시 추론가능한 타입을 포함하여야한다.

Usage

scala> 1 to 10
res6: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> 1 until 10
res7: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> 1 to 10 by 3
res8: scala.collection.immutable.Range = Range(1, 4, 7, 10)

scala> 10 to 1 by -3
res9: scala.collection.immutable.Range = Range(10, 7, 4, 1)

scala> 1L to 10L by 3
res10: scala.collection.immutable.NumericRange[Long] = NumericRange(1, 4, 7, 10)

scala> 1.1f to 10.3f by 3.1f
res11: scala.collection.immutable.NumericRange[Float] = NumericRange(1.1, 4.2, 7.2999997)

scala> 1.1 to 10.3 by 3.1
res12: scala.collection.immutable.NumericRange[Double] = NumericRange(1.1, 4.2, 7.300000000000001)

scala> 'a' to 'g' by 3
res13: scala.collection.immutable.NumericRange[Char] = NumericRange(a, d, g)

scala> BigInt(1) to BigInt(10) by 3
res16: scala.collection.immutable.NumericRange[BigInt] = NumericRange(1, 4, 7, 10)

scala> BigDecimal(1.1) to BigDecimal(10.3) by 3.1
res17: scala.collection.immutable.NumericRange.Inclusive[scala.math.BigDecimal] = NumericRange(1.1, 4.2, 7.3)

scala> 1 to 10L
<console>:12: error: type mismatch;
 found   : Long(10L)
 required: Int
       1 to 10L
            ^

scala> val r1 = 1 to 10 by 2
r1: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)

scala> r1.start
res19: Int = 1

scala> r1.end
res20: Int = 10

scala> r1.step
res21: Int = 2

scala> val r2 = r1
r2: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)

scala> Range.Long(1L, 2147483648L, 100)   //Int.MaxValue 보다 수열의 종료값이 커지면 Exclusive class로 구현? why?
res41: scala.collection.immutable.NumericRange.Exclusive[Long] = NumericRange(1, 101, 201, 301, 401, 501, 601, 701, 801, 901, 1001, 1101, 1201, 1301, 1401, 1501, 1601, 1701, 1801, 1901, 2001, 2101, 2201, 2301, 2401, 2501, 2601, 2701, 2801, 2901, 3001, 3101, 3201, 3301, 3401, 3501, 3601, 3701, 3801, 3901, 4001, 4101, 4201, 4301, 4401, 4501, 4601, 4701, 4801, 4901, 5001, 5101, 5201, 5301, 5401, 5501, 5601, 5701, 5801, 5901, 6001, 6101, 6201, 6301, 6401, 6501, 6601, 6701, 6801, 6901, 7001, 7101, 7201, 7301, 7401, 7501, 7601, 7701, 7801, 7901, 8001, 8101, 8201, 8301, 8401, 8501, 8601, 8701, 8801, 8901, 9001, 9101, 9201, 9301, 9401, 9501, 9601, 9701, 9801, 9901, 10001, 10101, 10201, 10301, 10401, 10501, 10601, 10701, 10801, 10901, 11001, 11101, 11201, 11301, 11401, 11501, 11601, 11701, 11801...

scala> 1L to 10L
res42: scala.collection.immutable.NumericRange.Inclusive[Long] = NumericRange(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Clone this wiki locally