0510.界範圍/過濾器(Range/Filter)

Range / Filter


Range






上下界


to( )

scala> for (fish <- 1 to 10) print(fish)   
12345678910
1 為 RichInt 富包覆器(Rich Wrapper), 由類型推演(inferred type)為 Int, 稱為下界, 調用 to(10) 方法, 10稱為上界. 返回一個 Range 實例命名為 fish.


until( )

scala> for (fish <- 1 until 10) print(fish)
123456789
until( ) 可排除上界



Number

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

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

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

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


scala> (1.to 10)
<console>:1: error: ')' expected but integer literal found.
       (1.to 10)
             ^


Char

scala> 'b' to 'h'
res12: scala.collection.immutable.NumericRange[Char] = NumericRange(b, c, d, e, f, g, h)





Filter



scala> "WisdomFish, ORG" filter ('a' to 'h' contains _)
res7: String = dh

scala> 'a' to 'h' contains _
res10: (Any) => Boolean = <function1>


Comments